android– 服务在Activity的’死亡’崩溃

android– 服务在Activity的’死亡’崩溃,第1张

概述我有一个启动服务的活动.在我的活动中:startService(newIntent(this,MyService.class));在我的服务中,onStart():/*Shownotification*/inticon=R.drawable.icon;tickerText=getResources().getString(R.string.app_name);longwhen=System.currentTimeMillis()

我有一个启动服务的活动.

在我的活动中:

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一起使用,因此当没有更多的工作要做时,服务会自动关闭.

总结

以上是内存溢出为你收集整理的android – 服务在Activity的’死亡’崩溃全部内容,希望文章能够帮你解决android – 服务在Activity的’死亡’崩溃所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1115935.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存