我希望标题本身能说明我的问题是什么.
我有一个在前台运行的 Service.
@Overridepublic int onStartCommand(意图意图,int标志,int startId){NotificationCompat.Builder builder = new NotificationCompat.Builder(这);PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,新意图(这个,WidgetFlashReceiver.class).setAction(Constants.ACTION_NOTIFICATION_CLICK),PendingIntent.FLAG_CANCEL_CURRENT);builder.setContentIntent(pendingIntent);builder.setOngoing(true);builder.setAutoCancel(false);builder.setContentTitle("示例服务");通知通知 = builder.build();通知.icon = R.drawable.ic_launcher;Notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;startForeground(NOTIFICATION_ID,通知);返回 START_STICKY;}但是当应用程序从最近的任务中被刷掉时,即使它是一个前台服务,这个服务也会被杀死.
感谢任何帮助.
解决方案看这个 评论关于Android错误,我找到了这个解决方案,为我解决了问题!
AlarmManager almgr = (AlarmManager)MyContext.getSystemService(Context.ALARM_SERVICE);Intent timerIntent = new Intent(MyUniqueLabel);timerIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);PendingIntent pendingOffLoadIntent = PendingIntent.getBroadcast(MyContext, 1, timerIntent, 0);你必须做这些事情才能让它工作.
1.) 调用 addFlags 和意图并将其传递到 FLAG_RECEIVER_FORGROUND
2.) 在 PendingIntent.getBroadcast 中使用非零请求代码
如果您忽略其中任何一个步骤,它将无法工作.
I hope title itself says what's my question is.
I have a Service which runs in foreground.
@Override public int onStartCommand(Intent intent, int flags, int startId) { NotificationCompat.Builder builder = new NotificationCompat.Builder( this); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, WidgetFlashReceiver.class) .setAction(Constants.ACTION_NOTIFICATION_CLICK), PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(pendingIntent); builder.setOngoing(true); builder.setAutoCancel(false); builder.setContentTitle("Sample Service"); Notification notification = builder.build(); notification.icon = R.drawable.ic_launcher; notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; startForeground(NOTIFICATION_ID, notification); return START_STICKY; }but this Service getting killed when app is swiped off from recent tasks even though it is a foreground Service.
Any help is appreciated.
解决方案Looking at this comment about the Android bug, I found this solution that solve the problem for me!
AlarmManager almgr = (AlarmManager)MyContext.getSystemService(Context.ALARM_SERVICE); Intent timerIntent = new Intent(MyUniqueLabel); timerIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingOffLoadIntent = PendingIntent.getBroadcast(MyContext, 1, timerIntent, 0);
you MUST do these things for it to work.
1.) Call addFlags and the intent and pass it in FLAG_RECEIVER_FORGROUND
2.) Use a non-zero request code in PendingIntent.getBroadcast
If you leave any of those steps out it will not work.
更多推荐
当应用程序被刷掉时前台服务被杀死
发布评论