Android服务在应用程序被终止后停止
我想创建一个Android服务在应用程序被终止后停止,android,service,android-service,Android,Service,Android Service,我想创建一个服务,即使在任务管理器关闭应用程序时也能运行。我已经创建了一个服务,然后记录了一条消息来检查它是否正在运行,我注意到它只有在应用程序正在运行或在前台时才能工作 服务类别: public class CallService extends Service { private final LocalBinder mBinder = new LocalBinder(); protected Handler handler; public class LocalB
服务
,即使在任务管理器关闭应用程序时也能运行。我已经创建了一个服务,然后记录了一条消息来检查它是否正在运行,我注意到它只有在应用程序正在运行或在前台时才能工作
服务类别:
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");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
startService(new Intent(this, CallService.class));
从我的主要活动开始服务:
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");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
startService(new Intent(this, CallService.class));
清单
<application>
...
<service
android:name=".activities.services.CallService">
</service>
</application>
...
我需要做什么改变?谢谢,各位在您的服务中,添加以下代码
@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);
}
我的手机太残忍了,在应用程序关闭的那一刻,前台服务就被扼杀了。我试过了,但也失败了:(使用Oppo A3S)