いつもお世話になっております。
Androidでアラーム機能を実装中なのですが、以下のようなバグが発生します。
1.アラームを設定する
2.キャンセルする
3.アラームを再度設定する
4.設定時刻になると、アラームが多重に起動してしまう
2の時点では正しくキャンセルされているようで、設定時刻になってもアラームは動きません。
4の段階で、複数回に渡ってIntentがとんでいるようです。
4の段階で、多重起動をやめて、一度だけアラームが起動するように修正したいと思っています。
登場人物とコードは以下の通りです。
すみませんが、どなたかよろしくお願いします。
【登場人物】
・AlarmSetActivity
-アラームを設定するアクティビティ(画面からのチェックボックスによってアラーム設定)
・AlarmReceiver
-アラームのレシーバー(BroadcastReceiverを継承)
・AlarmActivity
-アラームを鳴らすActivity。設定時刻になるとこの画面に遷移してアラームを鳴らす。
【コード】
lang
1//アラームを設定するアクティビティ 2AlarmSetActivity{ 3 private AlarmReceiver receiver; 4 //アラームを設定 5 public void onCheckboxClicked(View v) { 6 TimePicker timePicker = (TimePicker) findViewById(R.id.time_picker); 7 PendingIntent pi = getPendingIntent(); 8 AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService( 9 Context.ALARM_SERVICE); 10 11 if (((CheckBox) v).isChecked()) { 12 //チェックボックスがONならアラーム設定する 13 alarmManager.set(AlarmManager.RTC_WAKEUP, getStartTime(timePicker), 14 pi); 15 } else { 16 //チェックボックスがOFFならキャンセルする 17 alarmManager.cancel(pi); 18 pi.cancel(); 19 this.unregisterReceiver(receiver); 20 } 21 22 } 23 24 private PendingIntent getPendingIntent() { 25 //現アクティビティ(AlarmSetActivity)から(AlarmReceiver)へ送信するIntentを設定 26 27 IntentFilter filter = new IntentFilter(); 28 filter.addAction(Constants.ALARM); 29 receiver = new AlarmReceiver(); 30 registerReceiver(receiver, filter); 31 Intent broadcastIntent = new Intent(); 32 broadcastIntent.setAction(Constants.ALARM); 33 34 return PendingIntent.getBroadcast(getApplicationContext(), 0, 35 broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT); 36 37 } 38 39//アラームのレシーバー 40public class AlarmReceiver extends BroadcastReceiver { 41 42 boolean alarmSetFlg; 43 44 @Override 45 public void onReceive(Context context, Intent intent) { 46 Intent transCall = new Intent(context,AlarmActivity.class); 47 transCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 48 context.startActivity(transCall); 49 } 50} 51 52AndroidManifest.xml 53 54 <receiver 55 android:name="jp.exmple.alarm.AlarmReceiver" 56 android:permission="android.permission.Alarm" 57 android:process=":remote" > 58 <intent-filter> 59 <action android:name="Alarm" /> 60 </intent-filter> 61 </receiver> 62
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。