0

毎日同じ時間に通知を表示するアラームを実装しようとしています。

アクティビティで呼び出している関数は次のとおりです。

private void restartNotify() {
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Intent for our BroadcastReceiver 
    Intent intent = new Intent(this, AlarmReceiver.class);

    // PendingIntent for AlarmManager
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT );

    // In case we have already set up AlarmManager, we cancel.
    am.cancel(pendingIntent);



    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, pendingIntent);           
}

そして、ここに私のブロードキャストレシーバークラスがあります

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);   
    Notification notification = new Notification(R.drawable.icon_notif, context.getString(R.string.NotificationLaunchMssg), System.currentTimeMillis());

    // This is intent we want to launch when user clicks on the notification.
    Intent intentTL = new Intent(context, MyClass.class);

    notification.setLatestEventInfo(context, context.getString(R.string.NotificationTitle), context.getString(R.string.NotificationBody),               
    PendingIntent.getActivity(context, 0, intentTL, PendingIntent.FLAG_CANCEL_CURRENT));

    nm.notify(1, notification);

    //Here we set next notification, in day interval
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, pendingIntent); 
}
}

このコードでわかるように、テスト値 (+10000 ミリ秒) を使用しています。これは、アプリが起動してから 10 秒後にアラームをトリガーしようとしているだけだからです。しかし、それは機能しません。何も表示されません。アラームに問題があるのか​​、通知に問題があるのか​​わかりませんが、何も起こっていません。

理由はわかりますか?

ご協力いただきありがとうございます

編集: AlarmReceiver メソッドにいくつかのテスト コードを追加した後、このコードが実行されないことが判明しました。だから私はおそらくそれを適切に呼び出していません、何が問題なのですか?

4

1 に答える 1

0

このアプローチを使用しないでください。代わりにsetInexactRepeating(...)またはsetRepeating(...)を試してください。BroadcastReceiverがインテントを受信するたびにアラームを設定するために、BroadcastReceiverに余分な作業を与えるのはなぜですか。

ここに小さなコードがあります:

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            0, 10000, pendingIntent);
// The pending intent will the same as yours. 10000 is the 
// interval for between consecutive alarms

azertitiがコメントで述べたように、「登録されるまでに、その時間はすでに過去になっているでしょう。」したがって、0またはSystem.currentTimeMillis()を使用します。

于 2013-03-07T16:25:03.357 に答える