应用被杀死后,Android Service停止

编程入门 行业动态 更新时间:2024-10-12 05:45:27
本文介绍了应用被杀死后,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停止

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

发布评论

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

>www.elefans.com

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