如何防止重启正在运行的服务 - Android

3
我希望进行长时间的后台工作,同时我希望能够在用户进入活动时随时显示进度统计,并通过更新通知进行更新。
我在START_STICKY模式下启动了一个服务,然后将其绑定到我的活动并使用服务的公共方法运行进程。
一切都很顺利,直到我从最近的应用程序中关闭我的应用程序。
它会销毁并重新启动我的运行服务。
这就是问题所在。 “我不想让我的运行服务重新启动”
我希望我的服务可以持续运行而不被终止和重启。
我该如何做到我想做的事情呢?
为什么操作系统会重新启动正在运行的服务:/尽管
我尝试了START_NOT_STICKY,但它也关闭了服务。
3个回答

3

在Android 6及以上版本中,当用户从最近使用列表中移除应用时,前台服务不会停止。您可以通过在onCreate()中添加以下代码使您的服务成为前台服务:

final Intent launcherIntent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launcherIntent, 0);
final Notification.Builder builder = new Notification.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Test Notification")
        .setWhen(System.currentTimeMillis())
        .setContentIntent(pendingIntent);
final Notification notification;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    notification = builder.build();
}
else {
    //noinspection deprecation
    notification = builder.getNotification();
}
this.startForeground(NOTIFICATION_ID, notification);

在Android 6之前,当用户从任务列表中移除任务时,服务总是会被杀死。除了在onTaskRemoved()中进行干净关闭之外,您无法做任何事情来避免这种情况。

@Mehrad,我从您在其他帖子中的评论中了解到,您希望服务在用户从最近列表中删除应用程序时停止并且不会重新启动。我是否误解了? - Kevin Krumwiede
@Mehrad 抱歉,我更新了我的答案。 - Kevin Krumwiede
谢谢。但是,当您关闭应用程序时,音乐播放器如何不停止播放? - SemyColon.Me
@Mehrad,你能举个不这样做的例子吗?我使用Pandora,当你从最近列表中滑动它时,它会礼貌地停止服务,即使在6+上也是如此。 - Kevin Krumwiede
@Mehrad,我觉得我可能关于更改发生的时间有所错误。也许是在Android 5.0和5.1之间。 - Kevin Krumwiede
显示剩余3条评论

1

请尝试使用前台服务:

在启动服务的方法中:

Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);

现在在 onStartCommand() 中:
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();

阅读更多 简单的前台服务

或者您可以尝试像这样的代码:

onStartCommand() 需要返回 START_STICKY

在您的服务中覆盖 onDestroy() 方法:

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("EXIT", "ondestroy!");
    Intent broadcastIntent = new Intent();
    broadcastIntent.putExtra("broadcast.Message", "alarm, need to restart service");
    sendBroadcast(broadcastIntent);
}

现在需要实现广播接收器:

public class RestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
    context.startService(new Intent(context, YourService.class));
    }
}

0
check if service is running or not 

if(!isBackgroundServiceRunning(BackgroundServices.class))
        {
            Intent intent = new Intent(this,BackgroundServices.class);
            startService(intent);
        }

private boolean isBackgroundServiceRunning(Class<?> service)
    {
        ActivityManager manager = (ActivityManager)(getApplicationContext().getSystemService(ACTIVITY_SERVICE));

        if (manager != null)
        {
            for(ActivityManager.RunningServiceInfo info : manager.getRunningServices(Integer.MAX_VALUE))
            {
                if(service.getName().equals(info.service.getClassName()))
                    return true;
            }
        }
        return false;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接