【发布时间】:2018-12-29 16:52:35
【问题描述】:
我创建了一个服务,它的工作是在用户关闭应用程序时清除通知。一切运行良好,但有时当应用程序在后台运行超过 1 分钟时,服务会被终止(这意味着通知不会被取消)。 为什么会这样?我认为停止服务的唯一方法是使用 stopSelf() 或 stopService()。
public class OnClearFromRecentService extends Service {
private static final String TAG = "onClearFromRecentServic";
private NotificationManagerCompat mNotificationManagerCompat;
@Override
public void onCreate() {
super.onCreate();
mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service Started");
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service Destroyed");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Put code here which will be executed when app is closed from user.
Log.d(TAG, "onTaskRemoved was executed ");
if (mNotificationManagerCompat != null) {
mNotificationManagerCompat.cancelAll();
} else {
Log.d(TAG, "onTaskRemoved: mNotifManager is null!");
}
stopSelf();
}
}
我从启动屏幕 Activity 启动服务,如下所示:startService(new Intent(this, OnClearFromRecentService.class));
【问题讨论】:
-
哪个版本的安卓? 7.x+?
-
@emandt 我在 API 27 上运行这个应用程序
-
已经有很多关于这个“问题”的线程。从 SDK 26 开始,您必须创建一个前台服务,否则系统会在很短的时间后将其杀死。链接:developer.android.com/about/versions/oreo/android-8.0-changes
-
@emandt 你是对的。谢谢
-
@emandt 即使我打算使用服务在用户设备中加载文件列表。对我来说,该服务将从初始屏幕开始,并将继续工作直到完成工作。现在我的问题是假设如果用户在服务运行时最小化我的应用程序将在 Android 8.0 上运行,那么操作系统会在 1 分钟后终止服务吗?如果是,那么使用线程会帮助我克服这个问题吗?请帮忙。
标签: android android-components