在Android 12中,由于新引入的Doze API限制,设备可能会在睡眠模式下停止接收Fcm消息。为了解决这个问题,可以使用以下代码示例来实现一个定期保持设备唤醒状态的服务。
public class MyReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
MyIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class MyIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
try {
// 接收消息的代码
} finally {
wakeLock.release();
}
}
}
这样,只要存在未接收的消息,MyIntentService就会保持设备唤醒状态,直到所有消息都被接收。