在 Android 中关闭 activity 后的后台服务
Background service after closing activity in Android
我尝试创建应用程序,检查一些远程数据库的新闻和活动。当应用程序为 运行 时,它工作正常,应用程序检查,显示通知等。但是如果用户关闭应用程序,一切都会停止。是否可以在应用程序中创建在应用程序关闭后运行的后台服务(例如,用于发送本地通知)?如果可能的话,我必须做什么?
P.S。我了解 Firebase 和 Google Cloud,但我想创建独立的应用程序。
Services 几乎是您唯一的选择。但是您永远不知道您的服务何时被终止,并且随着 Android 的发展它会变得越来越严格。
As @Flo We said Service is the only option you can use
public class BackGroundService extends Service{
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Service","Started");
//Write your code here to run in background
return super.onStartCommand(intent, flags, startId);
}
}
使用 Intent 启动服务,不要在 onDestroy 上停止服务,它将在后台继续运行
我尝试创建应用程序,检查一些远程数据库的新闻和活动。当应用程序为 运行 时,它工作正常,应用程序检查,显示通知等。但是如果用户关闭应用程序,一切都会停止。是否可以在应用程序中创建在应用程序关闭后运行的后台服务(例如,用于发送本地通知)?如果可能的话,我必须做什么?
P.S。我了解 Firebase 和 Google Cloud,但我想创建独立的应用程序。
Services 几乎是您唯一的选择。但是您永远不知道您的服务何时被终止,并且随着 Android 的发展它会变得越来越严格。
As @Flo We said Service is the only option you can use
public class BackGroundService extends Service{
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Service","Started");
//Write your code here to run in background
return super.onStartCommand(intent, flags, startId);
}
}
使用 Intent 启动服务,不要在 onDestroy 上停止服务,它将在后台继续运行