Android 7 之后无法在启动时启动服务



我想在引导时启动一个服务。 此代码仅适用于 7 之前的 Android 版本。 我应该更改什么才能使其在较新版本上运行?我应该使用 JobScheduler 还是 WorkManager? 据我所知,计时器,处理程序和警报管理器已被弃用或具有不同的用途。 我怀疑在Android 7之后,他们删除了在启动时启动服务的选项,以节省电池寿命并避免降低手机速度。你能证实这一点吗?

这是我的广播接收器

package com.kev.boot21;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BroadcastReceiverOnBootComplete extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("tag","xyz broadcast 1");
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class);
context.startService(serviceIntent);
}
}
}

这是我的服务

package com.kev.boot21;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class AndroidServiceStartOnBoot extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("tag","xyz service");
}
}

这是我的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kev.boot21">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<receiver
android:name="com.kev.boot21.BroadcastReceiverOnBootComplete"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.kev.boot21.AndroidServiceStartOnBoot"></service>
<activity
android:name="com.kev.boot21.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

我发现WorkManager是处理这个问题的最佳方法。 在 Android 7、8 和 9 上重新启动后,我设法使用官方文档中的示例代码运行了 PeriodicWorkRequest: https://developer.android.com/topic/libraries/architecture/workmanager/basics

Android 10 的行为方式不同。重新启动后,PeriodicWorkRequest 仅在打开应用程序后工作。我想这是出于性能/安全原因

你需要通过调用 Context.registerReceiver(( 在代码中注册你的接收器,因为ACTION_BOOT_COMPLETED不再发送给通过 AndroidManifest 注册的接收器.xml

相关内容

最新更新