每当应用程序被杀死时服务停止 [英] Service stop's whenever app is killed
问题描述
START_STICKY 在我杀死应用程序时在我的设备中不起作用然后服务不会再次启动,我的设备名称是 Redmi Note 3 Pro,但是每当我在 android 模拟器中运行相同的应用程序时,它会在我终止时重新启动服务应用程序和服务不会停止,直到我通过 stopService() 方法停止它
START_STICKY don't work in my device whenever i kill my app then service don't start again, My device name is Redmi Note 3 Pro, but whenever i run same app in android emulator, it restarts the service when i kill the app and service don't stops until i stop it by stopService() method
请帮帮我
问题已解决
这样做:
设置>权限>自动启动然后打开我的应用程序的开关,大功告成!
我在此链接中找到了解决方案:解决方案链接
推荐答案
需要在manifest里面的service属性下添加android:process=:any_name".
You need to add "android:process=:any_name" in the manifest under the inside the service attributes.
例如
<service android:name=".MyService"
android:process=":MyService"
android:enabled="true"/>
下面是我的服务类的代码.
Below is the code of my Service class.
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("onCreate", "onCreate");
Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("servicedestroy", "servicedestroy");
Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
}
});
}
},
0,
5000);
return START_STICKY;
}
@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);
}
}
这篇关于每当应用程序被杀死时服务停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!