android 死亡自动启动,android – 服务在Activity的’死亡’崩溃

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

在我的活动中:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值