2011-09-13 8 views
2

以下は、毎日繰り返しアラームを設定するためのコードです。今私は2日後に私の警報を停止する必要があります。私は2日後にアラームを止めようとしましたが、動作していません。誰か助けてください。特定の時刻に2日後にアラームサービスを停止する方法はありますか?

Intent myIntent = new Intent(this, MyAlarmService.class); 

    pendingIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0); 

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 

    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, hour1); 
    calendar.set(Calendar.MINUTE, min1); 
    calendar.set(Calendar.SECOND, 0); 

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); 

    Toast.makeText(this, "Start Daily Alarm", Toast.LENGTH_LONG).show(); 

    //trying to cancel after 2 days 
    // add days to current date using Calendar.add method 

    calendar.add(Calendar.DATE, 2);  
    pendingIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0); 
    AlarmManager alarmManagerstop = (AlarmManager)getSystemService(ALARM_SERVICE); 
    alarmManagerstop.cancel(pendingIntent);  
+0

解決策はありますか? – Nik

答えて

2

ここでは、2番目のパラメータでシステム時間をミリ秒単位で渡します。

PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0); 

第2パラメータではリクエストコードがパスされたので、このようなことをしなければなりません。

private static int REQUEST = 1; 

設定したアラームごとにこのリクエストコードを保存する必要があります。このリクエストコードに同じ値を渡すと、アラームが無効になります。独自のリクエストコードを渡す必要があります。同じ要求コードがそのPendingIntentオブジェクトを検索し、このよう

private static int REQUEST = 1; 
PendingIntent.getService(this, REQUEST, myIntent, 0); 
AlarmManager alarmManagerstop = (AlarmManager)getSystemService(ALARM_SERVICE); 
alarmManagerstop.cancel(pendingIntent); 

、あなたがなるように、すべてのmilisecondの変化したシステムmilisecondを使用などなどのalarm.cancelメソッドに渡すために必要だったアラームを止めるために

リクエストコードも頻繁に変更されます。このミリ秒を使用するには、同じ値を使用できる静的変数の後に格納することができます。

+0

申し訳ありませんが、私は得られませんでした。私は、alarmmanagerstopの2番目の引数の要求を使用しようとしました。それは働いていない、私は2日後に自動的にアラームを鳴らすことを停止する必要があります。 – sachi

関連する問題