Как правильно отправлять повторяющиеся уведомления на Android - PullRequest
0 голосов
/ 03 июля 2019

Я устанавливаю повторное уведомление на Android, но будильник не отображается на моем устройстве.

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

Это метод, который запускает Alarm на MainActivity, он запускается каждый раз, когда приложение инициализируется.

 public void setAlarm(){
            alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

            alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(  MainActivity.this, 0, alarmIntent, 0);

            Calendar alarmStartTime = Calendar.getInstance();
            alarmStartTime.set(Calendar.HOUR_OF_DAY, 16);
            alarmStartTime.set(Calendar.MINUTE, 36);
            alarmStartTime.set(Calendar.SECOND, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
            Log.i(TAG,"Alarms set every day.");

        }

Это класс, который использует BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {

    private static final String TAG = "FOCUSALARM";


    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "BroadcastReceiver has received alarm intent.");
        Intent service1 = new Intent(context, AlarmService.class);
        context.startService(service1);

    }

}

И этот класс использует IntentService

public class AlarmService extends IntentService
{

    private static final int NOTIFICATION_ID = 101;
    private static final String TAG = "FOCUSALARM";


    public AlarmService() {
        super("AlarmService");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // don't notify if they've played in last 24 hr
        Log.i(TAG,"Alarm Service has started.");
        Context context = this.getApplicationContext();


        Intent mIntent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("test", "test");
        mIntent.putExtras(bundle);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Resources res = this.getResources();
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Focus");

        builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_launcher)
               // .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                .setTicker(res.getString(R.string.notification_title))
                .setAutoCancel(true)
                .setContentTitle(res.getString(R.string.notification_title))
                .setContentText(res.getString(R.string.notification_subject));


        NotificationManagerCompat notificationManager =  NotificationManagerCompat.from(this);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
        Log.i(TAG,"Notifications sent.");


    }

Когда я запускаю его, он показывает все журналы, но уведомление не появляется на устройстве.

I/FOCUSALARM: Alarms set every day.
I/FOCUSALARM: BroadcastReceiver has received alarm intent.
I/FOCUSALARM: Alarm Service has started.
I/FOCUSALARM: Notifications sent.

1 Ответ

1 голос
/ 03 июля 2019

Как сказал наш уважаемый автор @RobCo: в устройствах Oreo + вы должны создать канал уведомлений, для этого используйте следующий метод, как показано в документации для разработчиков Android:

 private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Hola";
            String description = "Focus bro";
            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 = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

Тогда просто используйте это жеОбъект NotificationManager в вашем уведомленииBuilder

  NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

        builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_launcher)
               // .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
               // .setTicker(res.getString(R.string.notification_title))
                .setAutoCancel(true)
                .setContentTitle(res.getString(R.string.notification_title))
                .setContentText(res.getString(R.string.notification_subject));


        notificationManager.notify(NOTIFICATION_ID, builder.build());
        Log.i(TAG,"Notifications sent.");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...