解决重新启动时自动触发警报的问题

时间:2018-07-12 05:02:20

标签: android notifications alarmmanager

我一直在尝试构建一个每小时在服务器上检查通知文件的应用程序。我已经使用警报管理器类成功实现了此操作,但是我现在面临的问题是,如果用户在重新启动后未启动应用程序,则不会在重新启动时触发警报。我想自动触发警报。经过一段时间的搜索,我发现重新启动时会启动一个活动,我知道这是一种不好的做法,但这可能是我唯一的出路。我想检查是否还有其他方式可以实现我想要的目标。我愿意不使用警报管理器类进行通知。请提供任何建议。

这是我的NotificationBootReceiver类

package com.example.quickstart;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

import java.io.IOException;

public class NotificationBootReceiver extends BroadcastReceiver {
    String txt = "";
    @Override
    public void onReceive(Context context, Intent intent) {
            Log.i("Message1234","Boot Successfull ");

            // Construct an intent that will execute the AlarmReceiver
            Intent i = new Intent(context, MyAlarmReceiver.class);
            // Create a PendingIntent to be triggered when the alarm goes off
            final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,
                    i, PendingIntent.FLAG_UPDATE_CURRENT);
            // Setup periodic alarm every every half hour from this point onwards
            long firstMillis = System.currentTimeMillis(); // alarm is set right away
            AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
            // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
            alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
                    2*60*60,pIntent);
            // alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
            //    AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);



    }
}

这是我用于NotificationBootReceiver的Android清单文件接收器。

  <receiver android:name=".NotificationBootReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>

1 个答案:

答案 0 :(得分:0)

在应用BootBroadcastReceiver中创建启动接收器:

public class BootBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context pContext, Intent intent) {
         // Start Alarm again...
    }
}

然后将此Receiver注册到您的manifest.xml

<receiver
android:name="com.xyz.BootBroadcastReceiver"
android:enabled="true" >
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

建议:

顺便说一句,我过去通过Alarm Manager实施了重复通知。当设备位于Doze mode中时,会有很多问题。

我建议您使用Work Manager的Google Architecture组件,该组件可与21或更低版本的Android完美配合。

更新 同时检查设置闹钟in this answer

的正确方法