java关闭服务_java – 活动关闭时服务停止

我已经阅读了一些与这个问题相关的答案,它们似乎都是一样的:

“使用START_STICKY运行您的服务”

“在前台运行您的服务”

“使用startService运行您的服务,不要绑定它”

我正在做所有这些事情,我的服务STILL关闭并在每次关闭活动时重新启动.

这不是IntentService.

我也没有在onClick处理程序中调用stopSelf或stopService.

从MainActivity启动我的服务:

svcIntent = new Intent(getBaseContext(),MyService.class);

startService(svcIntent);

在我的onStartCommand中:

// Enter foreground state

String title = "Service has been started...";

String subject = "Service is running...";

String body = "Monitoring your battery usage.";

Notification notification = new Notification(R.drawable.theicon,title,System.currentTimeMillis());

if (prefs.getBoolean("notificationSounds",true))

notification.defaults |= Notification.DEFAULT_SOUND;

else

notification.sound = null;

Intent notificationIntent = new Intent(this,MainActivity.class);

PendingIntent pendIntent = PendingIntent.getActivity(this,notificationIntent,0);

notification.setLatestEventInfo(this,subject,body,pendIntent);

startForeground(1500,notification);

在我的onStartCommand结束时:

...

// Release WakeLock

wl.release();

return START_STICKY;

UPDATE

我想出了什么导致它!但我不知道如何解决它.在我的服务中,我还使用服务中的AlarmManager在指定的时间内设置对服务的函数调用.

// Alarm manager setup for MyService

AlarmManager AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

svcIntent1 = new Intent(this,AlarmReceiver.class);

prefs.edit().putInt("initialBatt",initialBatt).apply();

svcIntent1.setAction("com.myApp.servicealarm");

pendingIntent = PendingIntent.getBroadcast(this,93,svcIntent1,PendingIntent.FLAG_UPDATE_CURRENT);

// Set the alarm

AM.set(AlarmManager.RTC_WAKEUP,timeNow + waitTime,pendingIntent);

我注意到如果我不注释AM.set调用来设置警报,即使有一个EMPTY onReceive,我的服务在闹钟响起时被杀死,在我最近的应用程序中刷掉我的应用程序之后.如果我注释掉设置的警报调用,那么在关闭我的应用程序后,服务永远不会被杀死并继续运行.有没有搞错?!我的算法功能需要这个警报!

这很奇怪.一旦闹钟响起,我的调试消息就不会打印,我的服务会重新启动.但第二次,在服务重新启动后,调试消息会打印并且程序成功执行.

我已经尝试了这个,它仍然发生在普通的广播接收器上.我还将我的代码剥离到我的服务和广播接收器的设置警报调用,同样的事情发生,所以这不是我的算法.显然,如果您有一个设置闹钟的前台服务,当闹钟响起时,您的服务将重新启动.

闭幕

这种行为似乎是由Android操作系统中的一个错误引起的,所以我不希望得到答案.如果你想自己看看这个bug,click here.我提供了一个你可以编译并重现问题的项目.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值