我有一个启动服务的活动.
在我的活动中:
startService(new Intent(this, MyService.class));
在我的服务中,onStart():
/* Show notification */
int icon = R.drawable.icon;
tickerText = getResources().getString(R.string.app_name);
long when = System.currentTimeMillis();
contentTitle = getResources().getString(R.string.app_name);
contentText = getResources().getString(R.string.running);
Intent notificationIntent = new Intent(this, activityClass).setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
startForeground(0, notification);
该服务有一个计时器,每隔3-4分钟就可以完成一些工作,并在可能的情况下向活动广播信息.当活动关闭时,服务应继续开展工作.
当我运行应用程序并返回主屏幕时,服务会继续运行.但过了一段时间我得到这些logcat消息,服务停止:
07-03 16:55:09.440: INFO/ActivityManager(583): Process com.myapp (pid 11665) has died.
07-03 16:55:09.440: WARN/ActivityManager(583): Scheduling restart of crashed service com.myapp/.MyService in 5000ms
我怎么能阻止这个?
解决方法:
When I run the app, and go back to the homescreen, the Service keeps running. But after a while I get these logcat messages, and the service stops… How can I prevent this?
一般来说,你没有.
服务并非旨在永远运行.太多开发人员已经启动了服务并且从未停止过它们.而且,在你的情况下,他们没有充分理由这样做.让内存中的服务暂停只是看着时钟滴答是浪费,特别是因为开发人员做了这样的事情,Android在他们坚持太久后“崩溃”了.
在您的情况下,请切换到使用AlarmManager,可能与IntentService一起使用,因此当没有更多的工作要做时,服务会自动关闭.
标签:crash,service,android
来源: https://codeday.me/bug/20190721/1495711.html