即使应用程序已从最近的应用程序中清除,也要继续服务



我遇到了一个小问题。

在我的应用程序中,服务是在用户成功登录后启动的。以前,如果应用程序被终止,服务需要停止。(比如,通过滑动从最近的应用程序列表中删除。)所以我们使用了android:stopWithTask="true"。现在,我们需要服务按原样运行,即使启动它的任务已从"最近的应用程序"列表中删除。因此,我将服务更改为包含android:stopWithTask="false"。但这似乎并不奏效。

相关代码:

以下是与服务相关的清单部分:

<service
    android:enabled="true"
    android:name=".MyService"
    android:exported="false"
    android:stopWithTask="false" />

在MyService.java中:

public class MyService extends AbstractService {
    @Override
    public void onStartService() {
        Intent intent = new Intent(this, MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new Notification(R.drawable.ic_launcher, "My network services", System.currentTimeMillis());
        notification.setLatestEventInfo(this, "AppName", "Message", pendingIntent);
        startForeground(MY_NOTIFICATION_ID, notification);  
    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Toast.makeText(getApplicationContext(), "onTaskRemoved called", Toast.LENGTH_LONG).show();
        System.out.println("onTaskRemoved called");
        super.onTaskRemoved(rootIntent);
    }
}

AbstractService.java是扩展Sevrice:的自定义类

public abstract class AbstractService extends Service {
    protected final String TAG = this.getClass().getName();
    @Override
    public void onCreate() {
        super.onCreate();
        onStartService();
        Log.i(TAG, "onCreate(): Service Started.");
    }
    @Override
    public final int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }
    @Override
    public final IBinder onBind(Intent intent) {
        return m_messenger.getBinder();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        onStopService();
        Log.i(TAG, "Service Stopped.");
    }    
    public abstract void onStartService();
    public abstract void onStopService();
    public abstract void onReceiveMessage(Message msg);
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Toast.makeText(getApplicationContext(), "AS onTaskRemoved called", Toast.LENGTH_LONG).show();
        super.onTaskRemoved(rootIntent);
    }
}

现在,如果我登录到应用程序中,MyService就会启动。之后,我按下主页按钮,所以应用程序移动到后台。现在,我从"最近的应用程序"列表中删除该应用程序。那时,我应该看到Toast和控制台消息,按照这个方法的描述:

public void onTaskRemoved(Intent rootIntent)

加入API 14级

如果服务当前正在运行,并且用户删除了来自服务应用程序的任务。如果你有设置ServiceInfo.FLAG_STOP_WITH_TASK,则不会收到此回调;相反,该服务将被简单地停止。

参数rootIntent用于启动正在删除的任务。

但我一点也没看到。服务在onStartCommand中返回START_STICKY,所以我认为onTaskRemoved应该与标志android:stopWithTask="false"一起被激发。

我遗漏了什么吗?

请告诉我,以防我需要添加一些代码,这些代码可能对找出问题很重要。

附言:到目前为止,我已在4.2.2中对此进行了测试。

附言:我刚刚在4.1.2中测试了相同的代码,Service在该代码上保持运行,我在日志中也收到了消息"onTaskRemoved called"。

我应该做些什么才能使它在所有版本中都有效?

只需遵循这些场景,您的服务和进程(在服务中运行的线程)将保持连续。

  1. 创建服务并在onStartCommand方法中使用START_SICKY作为返回值,如下所示:

    @Override
    public int onStartCommand(final Intent intent, 
                              final int flags,
                              final int startId) {
        //your code
        return START_STICKY;
    }  
    
  2. 以上代码将在销毁后重新启动服务,并始终保持运行,但如果您的应用程序从最近的应用程序中删除,则从服务运行的进程(线程)将停止工作。为了确保您的进程(线程)始终处于运行状态,您必须重写onTaskRemoved()方法并添加代码以重新启动任务,如下所示。

    @Override
    public void onTaskRemoved(Intent rootIntent){
        Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
        restartServiceTask.setPackage(getPackageName());    
        PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        myAlarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartPendingIntent);
        super.onTaskRemoved(rootIntent);
    }
    
  3. 启动如下服务

startService(new Intent(this,YourService.class));

在您的服务中,添加以下代码。在4.4.2 中对我来说很好

这是我遇到的一个变通方法,如果服务的进程在关闭应用程序时被终止,它可以很好地重新启动服务。

 @Override public void onTaskRemoved(Intent rootIntent){
     Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
     PendingIntent restartServicePendingIntent = PendingIntent.getService(
         getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
     AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
     alarmService.set(ELAPSED_REALTIME, elapsedRealtime() + 1000,
         restartServicePendingIntent);
     super.onTaskRemoved(rootIntent); 
}

如果您从Application类的子类绑定到您的服务并保持IBinder连接,则即使从最近的应用程序中删除了应用程序,该服务也将保持活动状态。

如果可以在服务运行时发出通知,则可以使用startForegroundService和startForeground来完成。

有三个重要的技巧:

  1. 调用startForegroundService,它创建了一个不限于绑定上下文的长期运行服务,并承诺稍后调用startForeground
  2. 返回onStartComand中的START_SICKY
  3. 按照(1)中的承诺,调用startForeground并发出通知

例如,如果您想运行TimerService,在您的TimerActivity中,您将执行以下操作:

private var timerService: TimerService? = null
private val timerServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(className: ComponentName, service: IBinder) {
        val binder = service as TimerService.Binder
        timerService = binder.getService()
    }
    override fun onServiceDisconnected(arg0: ComponentName) {
    }
}
override fun onCreate(savedInstanceState: Bundle?) {
    ...
    startButton.setOnClickListener {
        timerService?.startTimer(60L, 0L)
    }
}
override fun onStart() {
    super.onStart()
    Intent(this, TimerService::class.java).also {
        ContextCompat.startForegroundService(this, it) // that's the first trick
        bindService(it, timerServiceConnection, Context.BIND_AUTO_CREATE)
    }
}
override fun onStop() {
    super.onStop()
    unbindService(timerServiceConnection)
    timerService?.updateNotification(secondsRemaining)
}

您的TimerService将是这样的:

class TimerService : Service() {
    private val binder = Binder()
    private var serviceLooper: Looper? = null
    private var serviceHandler: ServiceHandler? = null
    private var timer: CountDownTimer? = null
    private val notificationUtil by lazy {
        NotificationUtil(this)
    }
    override fun onCreate() {
        HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND).apply {
            start()
            serviceLooper = looper
            serviceHandler = ServiceHandler(looper)
        }
    }
    override fun onBind(intent: Intent?): IBinder? = binder
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val timerRemaining = intent?.getLongExtra(EXTRA_REMAINING, 0) ?: 0L
        if (timerRemaining != 0L) {
            serviceHandler?.obtainMessage()?.also { msg ->
                msg.arg1 = startId
                msg.data.putLong(EXTRA_REMAINING, timerRemaining)
                serviceHandler?.sendMessage(msg)
            }
        }
        return START_STICKY // that's the second trick
    }
    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
    }
    fun startTimer(secondsRemaining: Long, id: Long) {
        updateNotification(secondsRemaining)
        Intent(this, TimerService::class.java).apply {
            putExtra(EXTRA_REMAINING, secondsRemaining)
        }.also {
            onStartCommand(it, 0, id.toInt())
        }
    }
    fun stopTimer() {
        timer?.cancel()
    }
    fun updateNotification(secondsRemaining: Long){
        val notification = NotificationCompat.Builder(this, NotificationUtil.CHANNEL_ID_TIMER)
                .setSmallIcon(R.drawable.ic_timer)
                .setAutoCancel(true)
                .setDefaults(0)
                .setContentTitle(secondsRemaining.formatSeconds())
                .setContentText("Timer")
                .setContentIntent(notificationUtil.getPendingIntentWithStack(this, TimerActivity::class.java))
                .setOngoing(true)
                .build()
        startForeground(NotificationUtil.NOTIFICATION_ID, notification) // that's the last trick
    }
    private fun sendMessage(remaining: Long) {
        Intent(TimerService::class.java.simpleName).apply {
            putExtra(EXTRA_REMAINING, remaining)
        }.also {
            LocalBroadcastManager.getInstance(this).sendBroadcast(it)
        }
    }
    private inner class ServiceHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            val secondsRemaining = msg.data.getLong(EXTRA_REMAINING)
            notificationUtil.showTimerStarted(secondsRemaining)
            timer = object : CountDownTimer(secondsRemaining * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    Log.i(this::class.java.simpleName, "tick ${(millisUntilFinished / 1000L).formatSeconds()}")
                    updateNotification(millisUntilFinished / 1000)
                    sendMessage(millisUntilFinished / 1000)
                }
                override fun onFinish() {
                    Log.i(this::class.java.simpleName, "finish")
                    notificationUtil.showTimerEnded()
                    sendMessage(0)
                    stopSelf()
                }
            }.start()
        }
    }
    inner class Binder : android.os.Binder() {
        // Return this instance of LocalService so clients can call public methods
        fun getService(): TimerService = this@TimerService
    }
    companion object {
        const val EXTRA_REMAINING = "EXTRA_REMAINING"
        const val NOTIFICATION_ID = 1 // cannot be 0
        fun Long.formatSeconds(): String {
            val s = this % 60
            val m = this / 60 % 60
            val h = this / (60 * 60) % 24
            return if (h > 0) String.format("%d:%02d:%02d", h, m, s)
            else String.format("%02d:%02d", m, s)
        }
    }
}

似乎从"最近的任务"中清除应用程序会杀死所有附加的任务。

也许你应该看看那里,找到一种方法,如果服务停止,可以重新启动:https://stackoverflow.com/a/22464640/4232337

编写我在服务类的oncreate()中添加的5行

像这样:

public class AlarmService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Intent iHeartBeatService = new Intent(AlarmService.this,
                AlarmService.class);
        PendingIntent piHeartBeatService = PendingIntent.getService(this, 0,
                iHeartBeatService, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(piHeartBeatService);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), 1000, piHeartBeatService);
    }
}

试试这个

public class MyService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        System.out.println("service created");
    }
    @SuppressLint("NewApi")
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        // TODO Auto-generated method stub
        System.out.println("onTaskRemoved");
        super.onTaskRemoved(rootIntent);
    }
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        System.out.println("Service started");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("Service is running");
            }
        }, 5000);
    }
}

相关内容

最新更新