每当应用被杀死时,服务停止

编程入门 行业动态 更新时间:2024-10-09 19:19:17
本文介绍了每当应用被杀死时,服务停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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); }

}

更多推荐

每当应用被杀死时,服务停止

本文发布于:2023-11-27 11:13:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637838.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:被杀   死时

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!