0

時間指定された通知 (毎日、午前 5:00) を配信したいので、次のコードで AlarmManager を使用してこれを実行しようとしました。

Intent appIntent = new Intent(this, NotificationService.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent penIntent = PendingIntent.getService(this, 0,
                appIntent, 0);

        alarmManager.cancel(penIntent);

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 5);
        cal.set(Calendar.MINUTE, 00);
        cal.set(Calendar.SECOND, 00);

        alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, penIntent);

NotificationService.class は (少なくとも重要な部分は) 次のようになります。

int id = 001;

            NotificationManager mNotifyMng = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    MainActivity.this).setSmallIcon(R.drawable.icon).setContentTitle("Test")
                    .setContentText("Test!");

            mNotifyMng.notify(id, mBuilder.build());
            stopSelf();

私はそれを機能させることができないようです。エミュレータの時計を 4:59 などに設定して 5:00 に変わるのを待っても、通知が表示されず、それをテストする別の方法がわかりません。それをテストする方法、または私のコードのバグを見つける方法を知っていることを願っています。

4

1 に答える 1

0

問題は、をキャンセルしたことPendingIntentだと思いますが、設定する前にもう一度作成する必要がありますalarmManager

  //cancel pendingIntent
  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  PendingIntent penIntent = PendingIntent.getService(this, 0,appIntent, 0);   
  alarmManager.cancel(penIntent);

  //reset pendingIntent
  Intent appIntent = new Intent(this, NotificationService.class);
  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  PendingIntent penIntent = PendingIntent.getService(this, 0,appIntent, 0);  
  Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 5);
    cal.set(Calendar.MINUTE, 00);
    cal.set(Calendar.SECOND, 00);

    alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(),                                                                      
          AlarmManager.INTERVAL_DAY, penIntent);  

a をキャンセルするPendingIntentには、最初に行ったのとまったく同じように作成し、そのままでAlarmManagerscancel()を呼び出す必要があります。ただし、アラームを設定するには、再度作成する必要があります。PendingIntent

**テストする方法を知っていることを願っています...

より良い方法があるかもしれませんが、テスト目的で、テストと本番の間で時間を変更するグローバル デバッグ フラグを設定することがあります。つまり、4 時間は 2 分かもしれません。1 日の時間帯は少し難しいかもしれませんが、時間、分、またはそれに近い時間に変更できます。適切なタイミングでトリガーされていることがわかったら、元に戻して、その時刻がいつ来るかをテストすることができますが、動作するはずであることがわかります。

于 2013-03-26T18:46:33.673 に答える