每当应用被杀死时,服务停止 [英] 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
请帮帮我
已解决的问题
完成此操作
Done this:
设置>权限>自动启动 然后打开我的应用程序的开关,然后完成!
我在此链接中找到了解决方案:解决方案链接
I got solution in this link: Solution Link
推荐答案
您需要在清单中的服务属性内添加"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"/>
下面是我的Service类的代码.
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屋!