я пытаюсь отправить уведомление, используя миллисекунды в Android? - PullRequest
0 голосов
/ 01 октября 2019

// вызов по нажатию кнопки

  scheduleNotification(getNotification(et_comments.getText().toString()), different );

// вместо задержки я использую другое (разное означает разницу во времени между next_action_date и текущей датой).

 private void scheduleNotification(Notification notification, long different) {
        Intent notificationIntent = new Intent( this, AlarmReceiver. class ) ;
        notificationIntent.putExtra(AlarmReceiver. NOTIFICATION_ID , 1 ) ;
        notificationIntent.putExtra(AlarmReceiver. NOTIFICATION , notification) ;
        PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;
       /* long futureInMillis = different;
        System.out.println("futureInMillis " + futureInMillis);*/
        long futureInMillis = SystemClock.elapsedRealtimeNanos () + different ;
        System.out.println("futureInMillis " + futureInMillis);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;
        assert alarmManager != null;
        alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , futureInMillis , pendingIntent) ;
    }
    private Notification getNotification (String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;
        builder.setContentTitle( "Scheduled Notification" ) ;
        builder.setContentText(content) ;
        builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
        builder.setAutoCancel( true ) ;
        builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
        return builder.build() ;
    }

// AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {

   public static String NOTIFICATION_ID = "notification-id" ;
    public static String NOTIFICATION = "notification" ;
    public void onReceive (Context context , Intent intent) {
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context. NOTIFICATION_SERVICE ) ;
        Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;
        if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
            int importance = NotificationManager. IMPORTANCE_HIGH ;
            NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel) ;
        }
        int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;
        assert notificationManager != null;
        notificationManager.notify(id , notification) ;
    }
}

// Используя этот код, я получаю мгновенное уведомление. что я должен сделать, пожалуйста, помогите !!!

1 Ответ

0 голосов
/ 01 октября 2019

В отличие от iOS, в Android нельзя запланировать уведомления напрямую с помощью API уведомлений ОС. Вместо этого вам необходимо:
1 - создать тревогу с помощью службы AlarmManager.
2 - обработать намерение после запуска ОС Android с помощью BroadcastReceiver.
3 - показать уведомление с помощью кодапохож на тот, который вы разместили в вопросе.

Исходя из вашего кода, я предполагаю, что вы пытаетесь использовать метод setWhen, чтобы установить, когда должно отображаться уведомление. Тем не менее, из документов вы можете видеть, что этот метод:

 /**
     * Set the time that the event occurred.  Notifications in the panel are
     * sorted by this time.
     */

Это означает, что эта информация используется только для определения порядка уведомлений, , но он не «планирует» уведомление в любомway.

Есть несколько моментов, касающихся того, как запрограммировать эту функцию. Взгляните на это, например:

https://www.raywenderlich.com/1214490-android-notifications-tutorial-getting-started

edit:

Из кода, который вы опубликовали. Будьте осторожны с этой строкой:

long futureInMillis = SystemClock.elapsedRealtimeNanos () + different

Вызов SystemClock.elapsedRealtimeNanos() вернет наносекунд вместо миллисекунд. В результате неправильная задержка.

Измените ее на:

SystemClock.elapsedRealtime() и убедитесь, что переменная different на самом деле миллисекунды, а не секунды или что-либо еще.

...