AlarmManger setПовторная остановка работы - PullRequest
0 голосов
/ 09 июня 2018

Я хочу запускать уведомление каждый час.

Я использую setRepeating в сервисе AlarmManager, проблема в том, что когда я закрываю свое приложение, менеджер не передает в BroadcastReceiver.

Мой BroadcastReceiver:

public class MyReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        Notification notification = new NotificationCompat.Builder(context, "notify_001")
                .setContentTitle("URL Database")
                .setSmallIcon(R.drawable.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setContentText("You didn't use the URLDatabase app for a while.\nYour urls feel lonely.")
                .setContentIntent(pendingIntent).build();

        NotificationManager manager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            NotificationChannel channel = new NotificationChannel("notify_001",
                    "URLDatabaseNotification",
                    NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }

        manager.notify(0, notification);
        Log.i("URLDatabase", "Received");
    }
}

Мой код для AlarmManager (я использую это в onCreate своей деятельности):

calendar = Calendar.getInstance();
intent = new Intent(this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager) this.getSystemService(ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60, pendingIntent);

Нужно ли создавать пользовательскую службу, которая будет работать вфон

1 Ответ

0 голосов
/ 09 июня 2018

Попробуйте этот код.Будут срабатывать каждые 10 минут.

Приемник вещания:

public class AlarmReceiver extends BroadcastReceiver {

public static final int REQUESTED_CODE_ALARM = 101;

@Override
public void onReceive(Context context, Intent intent) {

    // interval in minutes
    long fireTime = System.currentTimeMillis() + 10 * 60000;

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent alarmIntent = new Intent(context, AlarmReceiver.class);

    PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(
            context, REQUESTED_CODE_ALARM, alertNewsIntent, 0);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, fireTime, alarmPendingIntent);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, fireTime, alarmPendingIntent);
}}

Используйте этот код для включения тревоги (и срабатывания в первый раз):

Intent alarmIntent = new Intent(this, AlarmReceiver.class);
sendBroadcast(alarmIntent);

Для остановки тревоги:

public void stopAlertAlarm(){
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent alarmReceiver = new Intent(this, AlarmReceiver.class);
    PendingIntent alertNewsPendingIntent = PendingIntent.getBroadcast(
            this, AlarmReceiver.REQUESTED_CODE_ALARM, alarmReceiver, 0);

    alarmManager.cancel(alertNewsPendingIntent);
}

Важно: не забудьте зарегистрировать получателя в манифесте:

<receiver android:name=".services.AlarmReceiver" />
...