如何在应用程序被杀时运行服务?

时间:2016-10-06 06:51:21

标签: android

即使应用程序死于后台任务,我也希望运行我的服务。请有人给我一些建议。 (当我最小化应用程序时工作正常)

这里是我的代码:

public class MyService extends Service {
    private BroadcastReceiver mReceiver = null;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            if (ScreenReceiver.wasScreenOn) {
           Log.e("MYAPP", "SCREEN TURNED OFF");

            } else {
            // this is when onPause() is called when the screen state has not changed
        }
        return START_STICKY;   
       }

    @Override
    public void onDestroy() {
            super.onDestroy();
    }
} 

2 个答案:

答案 0 :(得分:2)

如果您的应用启动了您的服务,那么实际上您的服务正在主进程上运行。因此,当应用程序被杀死时,服务也将被停止。所以你可以做的是,从服务的onTaskRemoved方法发送广播,如下所示:

public class MyService extends Service {
    private BroadcastReceiver mReceiver = null;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            if (ScreenReceiver.wasScreenOn) {
           Log.e("MYAPP", "SCREEN TURNED OFF");

            } else {
            // this is when onPause() is called when the screen state has not changed
        }
        return START_STICKY;   
       }

    @Override
    public void onDestroy() {
            super.onDestroy();
    }

        @Override public void onTaskRemoved(Intent rootIntent){
              Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);
        } 

以下是您的广播接收器代码

import android.app.*;
import android.content.*;
import android.os.*;

public class ScreenReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, yourservice.class);
        context.startService(background);
    }

}

并有一个广播接收器,它将再次启动服务。我试过了。服务从所有类型的杀戮中重新开始。

答案 1 :(得分:0)

一旦被系统或用户杀死,您需要重新启动服务 Hope this will help you