Oreo Планирование уведомления через час

Даниэль, удивительное объяснение! Несколько слов по этому и хорошему списку указателя контекста выполнения this в случае обработчиков событий.

В двух словах this в JavaScript указывает объект, у которого (или из контекста выполнения которого) текущая функция была запущена, и она всегда доступна только для чтения, вы все равно не можете ее установить (такая попытка закончится сообщением «Недопустимая левая сторона в присваивании».

Для обработчиков событий: встроенный обработчики событий, такие как <element onclick="foo">, переопределяют любые другие обработчики, прикрепленные ранее и раньше, поэтому будьте осторожны, и лучше не вмешиваться в встроенное делегирование событий. И благодаря Заре Алавердян, которая вдохновила меня на этот список примеров через несогласие обсуждение:)

  • el.onclick = foo; // in the foo - obj
  • el.onclick = function () {this.style.color = '#fff';} // obj
  • el.onclick = function() {doSomething();} // In the doSomething - Window
  • el.addEventListener('click',foo,false) // in the foo - obj
  • el.attachEvent('onclick, function () { // this }') // window, all the compliance to IE :)
  • <button onclick="this.style.color = '#fff';"> // obj
  • <button onclick="foo"> // In the foo - window, but you can <button onclick="foo(this)">
0
задан Brandon 13 July 2018 в 16:26
поделиться

1 ответ

UPDATE:

Не забудьте добавить получателя в файл манифеста xml. Для этого вопроса:

Добавить в AndroidManifest.xml внутри тега приложения:

<receiver android:name=".MyReceiver" />

Пример: я сохраняю этот пример, он обновляет уведомление от Broadcast Receiver.

Создайте класс вещательного приемника, как показано, (не забудьте добавить приемник в файл манифеста xml)

public class NotificationUpdate extends BroadcastReceiver {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {
        //NEED A RESCHEDULE?
        updateNotification(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void updateNotification(Context context){
        Notification notification = new Notification.Builder(context.getApplicationContext(), "default")
                .setContentTitle("title")
                .setContentText("body")
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setAutoCancel(true)
                .build();
        NotificationManager manager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        if(manager!=null) manager.notify(123, notification);
    }
}

Пример вызова из Activity:

public class MainActivity extends AppCompatActivity {

    final long intervalPeriod=60*1000;
    AlarmManager mAlarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        NotificationChannel notificationChannel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel("default",
                    "primary", NotificationManager.IMPORTANCE_DEFAULT);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) manager.createNotificationChannel(notificationChannel);

            mAlarmManager=(AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE);
            PendingIntent intent=PendingIntent.getBroadcast(getApplicationContext(),1234,
                    new Intent(getApplicationContext(),NotificationUpdate.class),0);

            mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+intervalPeriod, intent);

        }
    }
1
ответ дан MRah 17 August 2018 в 12:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: