由于 Android 9 在线,我无法使用我的 JobIntentService 发送通知,该服务使用 BroadcastReceiver 启动。
它在 Android <= 8.1 的其他设备上运行良好,我可以立即收到通知。有时它也适用于 Android P,但有时系统不会使用 AlarmManager 触发已注册的服务!或者我无法收到它。
出了什么问题?报警接收器.java
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "AlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
onBoot(context);
}
Log.d("action", "i recieved an action");
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("Push_Message", "No Content");
int type = bundle.getInt("Push_Type", -1);
Intent newIntent = new Intent(context, AppJobService.class);
newIntent.putExtra("Push_Message", message);
newIntent.putExtra("Push_Type", type);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
AppJobService.enqueueWork(context, AppJobService.class, AppJobService.JOB_ID, newIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
AndroidManifest.xml 中的权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
在这里,我已将 Receiver 添加到 AndroidManifest.xml
<receiver
android:name=".notifications.AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
我在一个继承自 JobIntentService 的类中以这种方式向 AlarmManager 注册服务
AppJobService.java
public void sendTimedNotification(String message, int type, long timeInMillis) {
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("Push_Message", message);
intent.putExtra("Push_Type", type);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timeInMillis, sender);
}