应用被杀死后,Android Service停止 [英] Android Service stops after the app is killed
本文介绍了应用被杀死后,Android Service停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个service
,即使从任务管理器关闭该应用程序也可以运行.我创建了一个服务,然后记录了一条消息以检查它是否正在运行,并且我注意到它仅在应用程序正在运行或在前台运行时才起作用.
I want to create a service
that runs even when the app is closed from the Task manager. I have created a service and then Logged a message to check if it's running and I noticed that it works only if if the app is running or in foreground.
服务等级:
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>
我必须进行哪些更改?谢谢,伙计们
What changes do I have to make? Thanks, folks
推荐答案
在您的服务中,添加以下代码.
In your service, add the following code.
@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);
}
这篇关于应用被杀死后,Android Service停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文