Создание службы для запуска в фоновом режиме и создания уведомлений - PullRequest
1 голос
/ 06 апреля 2020

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

Однако теперь со всеми ответами есть проблема, они хотят использовать WakefulBroadcastReceiver, которая сейчас устарела. Я понимаю, что теперь мне нужно использовать JobService, поэтому я попытался обновить код из предыдущего поста, чтобы он выглядел следующим образом (частично используя этот урок https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html)

public class NotificationEventReceiver extends JobService {

    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
    private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
    private static final int NOTIFICATIONS_INTERVAL = 1;

    public static void setupAlarm(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = getStartPendingIntent(context);
        alarmManager.setRepeating(AlarmManager.RTC,
                getTriggerAt(new Date()),
                NOTIFICATIONS_INTERVAL * AlarmManager.INTERVAL_DAY,
                alarmIntent);
    }

    private static long getTriggerAt(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
        calendar.set(Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 0);
        return calendar.getTimeInMillis();
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Intent service = new Intent(getApplicationContext(), NotificationIntentService.class);
        getApplicationContext().startService(service);
        setupAlarm(getApplicationContext()); // reschedule the job
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }

    private static PendingIntent getStartPendingIntent(Context context) {
        Intent intent = new Intent(context, NotificationEventReceiver.class);
        intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public static PendingIntent getDeleteIntent(Context context) {
        Intent intent = new Intent(context, NotificationEventReceiver.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}

И затем в манифесте Android 1012 *

    <service
        android:name=".NotificationEventReceiver"
        android:label="Notification Service"
        android:permission="android.permission.BIND_JOB_SERVICE" />

При запуске я больше не получаю никаких уведомлений, поэтому я явно что-то сделал не так, но я в растерянности, так как мне нужно сделать.

1 Ответ

1 голос
/ 14 апреля 2020

У меня недавно была эта проблема, и я решил ее с помощью приемника вещания.

Несмотря на то, что WakefulBroadcastReceiver устарел, его родительский класс не устарел.

Intent intent = new Intent(context, ClassReminderReceiver.class);

  PendingIntent pendingIntent = PendingIntent.getBroadcast(
     context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  AlarmManager alarmManager = (AlarmManager) 
     context.getSystemService(Context.ALARM_SERVICE);
  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), 
        AlarmManager.INTERVAL_DAY, pendingIntent);

Я использую диспетчер тревог setRepeating () и RTC_WAKEUP, см. Руководство по соответствующим типам тревог для соответствующего типа тревоги

также, см. Ссылку ниже, чтобы увидеть лучшие практики по тревогам. Рекомендации по оповещениям

Вы должны указать приемник вещания в манифесте

<receiver
        android:name=".ClassReminderReceiver"
        android:enabled="true"
        android:exported="true" />

Это класс приемника вещания

 public class ClassReminderReceiver extends BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {
      ClassReminderNotification.notify(context);
     }
  }

Вы сказали, что хотите создать уведомление, но, как упомянул @Chuong Le Van, я не вижу, где вы определяете уведомление в своем коде.

Ниже приведен класс ClassNotification

class ClassReminderNotification {

static void notify(Context context) {
    createNotificationChannel(context);
    // Create an explicit intent for an Activity in your app
    Intent intent = new Intent(context, YourActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);


    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, 
          "class_reminder")
            .setSmallIcon(R.drawable.ic_school_black_24dp)
            .setContentTitle("Your Notification Title")
            .setContentText("Your Text")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    NotificationManagerCompat notificationManager = 
    NotificationManagerCompat.from(context);

    // notificationId is a unique int for each notification that you must define
    int notificationId = 1;
    notificationManager.notify(notificationId, builder.build());

}

private static void createNotificationChannel(Context context) {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    String CHANNEL_ID = "class_reminder";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.channel_name);
        String description = context.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, 
          importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = 
           context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
        }
    }
}

Вот руководство гугла Обзор уведомлений Обзор уведомлений

Здесь также находится официальное руководство по созданию уведомления Официальное руководство по созданию уведомления .

Надеюсь, это поможет.

...