Android闹钟触发通知

时间:2015-08-22 16:46:22

标签: android android-intent android-broadcast android-alarms

我需要Android AlarmManager来触发通知。

我正在按如下方式创建闹钟:

    private void createAlarm() {
    AlarmManager mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent mNotificationReceiverIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
    PendingIntent mNotificationReceiverPendingIntent =
            PendingIntent.getBroadcast(MainActivity.this,0,mNotificationReceiverIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    mAlarmManager.setRepeating(AlarmManager.RTC, SystemClock.currentThreadTimeMillis()
            + ALARM_DELAY, ALARM_DELAY, mNotificationReceiverPendingIntent);
    Log.i(TAG,"Alarm created");
    }

AlarmNotificationReceiver是

public class AlarmNotificationReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Log.i(TAG,"Alarm Notification received");
}
}
但是,我从来没有看到过logmessage。我已经看到使用“adb shell dumpsys alarm”发出警报:

  u0a54:de.fabian_nick.dailyselfie +709ms running, 0 wakeups:

+709ms 0 wakes 12 alarms: *alarm*:de.fabian_nick.dailyselfie/.AlarmNotificationReceiver

(至少如果我读得正确的话)。 所以我假设我创建的PendingIntent由于某种原因没有被BroadcastReceiver接收。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

我需要添加

<receiver android:name=".AlarmNotificationReceiver"></receiver>

到我的AndroidManifest.xml

答案 1 :(得分:0)

在您的 AndroidManifest.xml 中添加以下行

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