我正在制作一个应用程序,需要在设备开机到关机期间始终运行服务,即使应用程序已关闭。在Android系统中是否可以实现这一点?
我正在制作一个应用程序,需要在设备开机到关机期间始终运行服务,即使应用程序已关闭。在Android系统中是否可以实现这一点?
首先,您需要获得许可。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
然后创建一个广播接收器:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Startup extends BroadcastReceiver {
public Startup() {
}
@Override
public void onReceive(Context context, Intent intent) {
// start your service here
context.startService(new Intent(context, SERVICE.class));
}
}
在清单文件中将此广播接收器注册为
<receiver android:name="YOUR_PACKAGE.Startup" >
<!-- This intent filter receives the boot completed event -->
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
注意:服务也不能保证从设备启动到设备关闭始终运行,因为在极端情况下,Android系统可能会关闭该服务以获取额外的内存。
IntentService
服务,如果在处理意图时服务被终止,它将被重新启动。我还没有想出其他的方法。 - Rachit Mishracontext.startService(new Intent(context, SERVICE.class));
在 Android 版本 >= Oreo 中会抛出 IllegalStateExeption,因为如果应用程序在后台,则无法再启动服务。请查看此链接 https://medium.com/@berriz_/service-and-boot-completed-on-android-o-6a389eae50f1。 - Fivos