2017-02-02 7 views
1

私はAlarmManagerを使用して時間を設定し、今後何らかの作業を行う予定です。ほとんどの場合、問題なくうまく動作します。しかし、時には(時には)、警報が発せられません。問題を再現するのは難しく、その理由はまだ分かりません。 私はいくつかのOSバージョンでこの問題を抱えています:4.4,5.1,6.0,6.1,7.0。AlarmManagerが不安定です

私は既にWakefulBroadcastReceiverを使用してWakelockでサービスを開始していますが、それでも問題は発生します。

以下は、アラームをスケジュールするための私のコードです。

Intent alarmIntent = new Intent(context, AlarmReceiver.class); 
     alarmIntent.putExtra("todo_id", myTodo.getId()); 
     alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(context, myTodo.getId(), alarmIntent, PendingIntent.FLAG_ONE_SHOT); 

     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), pendingIntent); 
      alarmManager.setAlarmClock(alarmClockInfo, pendingIntent); 
     } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
      alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
     } else { 
      alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
     } 


public class AlarmReceiver extends WakefulBroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     LogUtil.debug("onReceive()"); 
     if (null != intent.getExtras()) { 
      int id = intent.getIntExtra("todo_id", -1); 
      if (id != -1) { 
       Intent myIntent = new Intent(context, AlarmService.class); 
       myIntent.putExtra("todo_id", id); 
       LogUtil.debug("Receiver receive todo id: "+id); 
       startWakefulService(context, myIntent); 
      } 
     } 



    } 
} 





public class AlarmService extends Service { 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     LogUtil.debug("Service onStartCommand"); 

     int id = intent.getIntExtra("todo_id", -1); 
     LogUtil.debug("Service receive todo id: " + id); 

     // do some stuff here 


     AlarmReceiver.completeWakefulIntent(intent); 
     return START_REDELIVER_INTENT; 
} 

誰も私と同じ問題がありますか?あなたの解決策は何ですか? この問題はAndroid SDKからのもので、AlarmManagerの作業が不安定になっている可能性があります。

+0

同じ問題があってもうまくいきませんでした7.0 – Akshay

+0

私はいくつかのidsがあなたのケースで-1となると思います。 – Mike

+0

@Mike、いくつかのidsが-1になる理由をもっと詳しく教えてください。 – CauCuKien

答えて

1

私は同じ問題を抱えていましたが、私はこの問題をAlarmReceiverのすべてのロジックを実行することで解決しました。私は警報論理を保持している受信機でもサービスを開始していました。しかし、いったん私はアラーム受信機に私のコードを移動すると正常に動作します。私の問題は、私は私のサービスを終了していなかった、それは実行し続けていくつかの問題を引き起こしたり、他の理由かもしれないが、それは私の問題を解決した。この手助けがあれば試してみてください。

+0

私は、結果を後で教えてくれます。 – CauCuKien

+0

AlarmReceiverでウェイクロックを取得する必要がありますか? – CauCuKien

+0

私はあなたの方法を使用しようとしましたが、いくつかの問題があります。私はSQLiteに関連したものにアクセスし、ネットワークコールを呼び出す必要があるので、UIスレッド上で実行されるため、レシーバは適切ではありません。 – CauCuKien

関連する問題