1

由于 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);

    }
4

1 回答 1

0

根据文件:

设备在打盹模式下空闲时不会触发警报。任何预定的警报都将推迟到设备退出打盹。如果您需要确保即使设备处于空闲状态也能完成您的工作,有几个选项可供选择。您可以使用 setAndAllowWhileIdle() 或 setExactAndAllowWhileIdle() 来保证警报会执行。另一种选择是使用新的 WorkManager API,该 API 旨在一次性或定期执行后台工作。有关更多信息,请参阅使用 WorkManager 安排任务。

看看https://developer.android.com/training/scheduling/alarms

于 2018-08-14T14:08:09.787 回答