警报管理器不工作

AlarmManager is not working

您好,我正在开发演示应用程序,我在其中使用 AlarmManager 每天在 8:00 安排服务。我正在使用 Calendar 在 8:00 时钟安排服务,但此 AlarmManager 不是 运行 计划时间甚至 30 分钟后的服务。

下面是我的代码:-

public static void scheduleVerseNotificationService(Context mContext) {
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, DailyVerseNotificationService.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);

    // Set the alarm to start at approximately 08:00 morning.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 8);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

}

TestService.java

public class TestService extends Service {
    public TestService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        try {
            // Code
        } catch (Exception e) {
            Logger.e(Constants.TAG, e.getMessage());
        }
        stopSelf();
    }
}

AndroidManifest.xml

<service
    android:name="com.service.TestService"
    android:enabled="true"
    android:exported="true" />

提前致谢。

两种解决方案: 1) 而不是

    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);

使用

    PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, 0);

2) 如果这不起作用,那么您需要创建一个警报接收器

 public class AlarmReceiver extends WakefulBroadcastReceiver {
    @Override
     public void onReceive(Context context, Intent intent) {

       Log.i("AlarmReceiver", "onReceive");

      ComponentName comp = new ComponentName(context.getPackageName(),
        DailyVerseNotificationService.class.getName());
      startWakefulService(context, (intent.setComponent(comp)));
      setResultCode(Activity.RESULT_OK);
     }

 }

将您的待定意向更改为

     Intent intent = new Intent(mContext, AlarmReciever.class);
     PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);

在清单中注册接收器

     <receiver android:name="com.example.myApp.AlarmReceiver" /> 

最后将权限放入清单

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

另请参考: https://developer.android.com/training/scheduling/alarms.html

以上link将指导您在"Start an Alarm When the Device Boots"部分创建引导接收器。

还要确保设置:

    calendar.set(Calendar.MINUTE, 0); // for 0 minutes
    calendar.set(Calendar.SECOND, 0); // for 0 seconds

只是添加到 Bhushan 答案。

确保在启动时设置警报,因为如果设备关闭并重新启动,所有注册的警报都会被清除。