应用程序被杀后Android服务停止

时间:2017-04-09 19:18:09

标签: android service android-service

我想创建一个service即使应用程序从任务管理器关闭也会运行。我创建了一个服务,然后记录了一条消息,检查它是否正在运行,我注意到只有当应用程序正在运行或处于前台时它才有效。

服务类:

public class CallService extends Service {

    private final LocalBinder mBinder = new LocalBinder();
    protected Handler handler;

    public class LocalBinder extends Binder {
        public CallService getService() {
            return CallService .this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TESTINGSERVICE", "Service is running");
    }
}

从我的MainActivity启动服务:

@Override
protected void onCreate(Bundle savedInstanceState) {
   ...
   startService(new Intent(this, CallService.class));

清单

<application>
   ...
   <service
      android:name=".activities.services.CallService">
   </service>
</application>

我必须做出哪些改变?谢谢,伙计们

2 个答案:

答案 0 :(得分:9)

在您的服务中,添加以下代码。

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }

答案 1 :(得分:0)

如果kelebro63的解决方案不起作用,最好的解决方案是添加stopSelf()并在服务中增加70到100毫秒之间的超时。

@Override
   public void onTaskRemoved(Intent rootIntent) {
       stopSelf();
       Log.e("stopservice","stopServices");
       try {
           Thread.sleep(100);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       super.onTaskRemoved(rootIntent);
   }
相关问题