运行 一个 Android 服务被最近 activity 刷出后,如何在后台 运行?

How to run an Android service in Background after it is swiped out by Recent activity?

我有一个应该始终 运行 的后台服务。 它应该等待传入的电子邮件,当电子邮件到达时(给我的旧phone),它会触发一个动作。 (向我的新 phone 发送短信)。不是一个聪明的用户案例,只是学习 android.

但是,如果我将应用程序保留在 'Recent' 个应用程序中,上述所有操作都可以正常工作。我把它刷掉的那一刻,它不起作用。

关于如何实现此目标的任何想法?

我在 Whatsapp、Facebook 等一些应用程序中看到。即使我们滑动关闭后,也有后台服务 运行 收听新通知等。 我如何使用我的应用程序实现?

为此创建粘性服务:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

START_STICKY 如果此服务的进程在启动时被终止(从 onStartCommand(Intent, int, int) 返回后),则将其保留在启动状态但不保留此传递的意图。稍后系统将尝试重新创建服务。因为是启动状态,所以会保证在创建新的服务实例后调用onStartCommand(Intent, int, int);如果没有任何挂起的启动命令要传递给服务,它将使用空意图对象调用。

为此,您需要使服务具有粘性 return START_STICKY onStartCommand 服务。并且在文档中提到如果进程被终止系统将再次重新创建

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

public class MyService extends Service {

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler.postDelayed(run, 1000);
        return Service.START_STICKY;
    }

    private Runnable run = new Runnable() {

        @Override
        public void run() {
            handler.removeCallbacks(run);
            handler.sendEmptyMessage(0);
        }
    };
    private Handler handler = new Handler() {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.Handler#handleMessage(android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
            Log.e("handleMessage", "" + System.currentTimeMillis());
            handler.postAtTime(run, 1000);
        }

    };
}