[英]Android background task issue
我的Android服务类遇到后台任务问题,每当我从应用程序启动服务并返回设备上的主菜单,直到服务正常运行为止,但是当我从最近的应用程序列表中清除所有后台应用程序时,服务也会停止。 所以我该如何避免这种事情。
您的子IntentService
类上的onStartCommand
方法应返回Service.START_STICKY
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//some code...
return Service.START_STICKY;
}
然后该服务将继续在后台运行。
当我从最近的应用程序列表中清除所有后台应用程序时,该服务也将停止
您可以使用startForeground()
将其声明为前台服务。 前台服务必须为状态栏提供一个通知,该通知位于“正在进行”标题下,这意味着除非该服务已停止或从前台删除,否则无法取消该通知。
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.