2017-10-30 27 views
0

通知を特定の時刻に設定しようとしていますが、通知が正確な時刻に表示されません。アラームマネージャとブロードキャストレシーバが正しい時刻に通知を表示しない - Android

時々、通知が正しい時刻に到着し、時には10-15秒の遅延があります。

private void showNotification(long lastScratched) { 

     Intent intent = new Intent(getActivity(), NotificationReceiver.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

     lastScratched = lastScratched + timeInterval; 

     AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE); 
     alarmManager.set(AlarmManager.RTC_WAKEUP, lastScratched, pendingIntent); 
     Log.e("MyNotification", "Next Notification Time : "+lastScratched+""); 
    } 

NotificationReceiver.java

public class NotificationReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

     Intent myIntent = new Intent(context, MainActivity.class); 
     myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

     Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "my_channel_01") 
       .setContentIntent(pendingIntent) 
       .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_icon)) 
       .setSmallIcon(R.drawable.app_icon) 
       .setContentTitle("Notification Title") 
       .setContentText("Notification Text") 
       //.setPriority(Notification.PRIORITY_MAX) 
       .setSound(alarmSound) 
       .setAutoCancel(true); 

     notificationManager.notify(100, builder.build()); 
    } 
} 

答えて

1

使用setExactAndAllowWhileIdleまたはJobSchreduler

setExactAndAllowWhileIdleのためには使用することができます。

AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); 
+0

setExactAndAllowWhileIdleとsetExactの違いは何ですか?どちらを私はsetExactまたはsetExactAndAllowWhileIdleを使うべきですか? –

+1

** setExactAndAllowWhileIdle **は、Androidがスリープ状態になる低電力モードで動作します。 – Ghost

関連する問題