0

Друзья, я не давно начал на андроид писать и опять у меня вопрос по уведомлениям, сделал по примерам, работает на всех эмуляторах, а у пользователя, как минимум одного вместо срабатывания блымкает экран и все, уведомление не возникает, 7 версии андроид, в настройках уведомления разрешены, в чем может быть косяк? Посмотрите код плиз

В фрагменте устанавливаю время срабатывания:

if (Core.get().getPreferences().getBoolean("reminder_drink_switch",false)) {
        Intent intentWater = new Intent(getContext(), MainBaseService.class);
        intentWater.setAction(MainBaseService.ACTION_WATER_ALARM);

        PendingIntent sender2 = PendingIntent.getService(getContext(), 2, intentWater, 0);

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

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.HOUR_OF_DAY, Core.get().getPreferences().getInt("reminderDrinkHour", 0));
        calendar.add(Calendar.MINUTE, Core.get().getPreferences().getInt("reminderDrinkMinute", 0));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND,0);

        long sdl = calendar.getTimeInMillis();

        alarmManager.set(AlarmManager.RTC_WAKEUP, sdl, sender2);
    }

В классе, где сервис

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_PROCESS_ASSET_BASE.equals(action)) {
            handleProcessAssetBase();
        } else if (ACTION_CHECK_BASE_UPDATES.equals(action)) {
            handleCheckBaseUpdates();
        } else if (ACTION_PROCESS_OLD_BASE.equals(action)) {
            handleProcessOldBase();
        } else if (ACTION_BASE_UPDATE.equals(action)) {
            handleBaseUpdate(intent.getStringExtra(EXTRA_MAIN_BASE_URL), intent.getStringExtra(EXTRA_MAIN_BASE_VERSION));
        } else if (ACTION_PROCESS_BURNER_BASE.equals(action)) {
            handleProcessBurnerBase();
        } else if (ACTION_WATER_ALARM.equals(action)) {
            showWaterNotification();
        } else if (ACTION_EATINGS_ALARM.equals(action)) {
            showEatingsNotification();
        }
    }
}

private void showBackgroundNotification(int requestCode, Notification notification, Bundle extras) {
    Intent intent = new Intent(ACTION_BROADCAST_NOTIFICATION);
    intent.putExtra(REQUEST_CODE, requestCode);
    intent.putExtra(NOTIFICATION, notification);
    if(extras != null) intent.putExtras(extras);
    sendOrderedBroadcast(intent, PERMISSION_PRIVATE, null, null, Activity.RESULT_OK, null, null);
}

    private void showWaterNotification() {
    Intent intent = new Intent(this, MainActivity.class);

    PendingIntent pi = PendingIntent.getActivity(this, NOTIFICATION_WATER_ID, intent, 0);
    Context context = getApplicationContext();
    Resources res = context.getResources();
    Notification notification = new NotificationCompat.Builder(this)
            .setTicker(getString(R.string.water_notify))
            .setSmallIcon(R.drawable.ic_water_notify)

            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.apple64))
            .setContentTitle(getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.water_notify)))
            .setContentText(getString(R.string.water_notify))
            .setContentIntent(pi)
            .setAutoCancel(true)
            .build();

    boolean sleep = true;

    final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    try {
        Date now = new Date();
        now = dateFormat.parse(dateFormat.format(now.getTime()));
        Date nachalo = dateFormat.parse("7:00");
        Date konec = dateFormat.parse("22:00");
        if (now.after(nachalo) && now.before(konec))
            sleep = false;
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (!sleep) {
        if (Core.get().getPreferences().getBoolean("vibrate", true))
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        if (Core.get().getPreferences().getBoolean("sound", true))
            notification.defaults |= Notification.DEFAULT_SOUND;
    }

   showBackgroundNotification(NOTIFICATION_WATER_ID, notification, null);
}

Класс ресивер

public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {        
    int requestCode = intent.getIntExtra(MainBaseService.REQUEST_CODE, 0);
    Notification notification = intent.getParcelableExtra(MainBaseService.NOTIFICATION);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    if (notification!=null)
    notificationManager.notify(requestCode, notification);
}

}

В манифесте есть:

<uses-permission android:name="android.permission.VIBRATE" />

<receiver
        android:name=".NotificationReceiver"
        android:exported="false">
        <intent-filter android:priority="-999">
            <action android:name="ru.hikisoft.calories.mainBase.broadcast.NOTIFICATION" />
        </intent-filter>
    </receiver>

2 ответа 2

0

Алармы - это головная боль. С каждым новым API вводят какие-то ограничения и "особенности". Например, начиная с API 19 система не гарантирует доставку аларма вовремя, а с API 23 ввели Dozen Mode. Ну и соответственно добавлялись новые методы установки Alarm. Вот так примерно должна выглядеть процедура установки:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
          {
            final AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(time, pendingIntent);
            am.setAlarmClock(alarmClockInfo, pi);
          }
      else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            am.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
      else
            am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
5
  • сам аларм похоже срабатывает и просто через set, а вот вместо уведомления у пользователя идет схлопывание текущей активити и выбрасывает в mainactivity, тестировал в генимошн у себя на компе на этих версиях андроида, все срабатывает как надо, уведомления формируются, схлапывание не происходит 13 окт 2017 в 8:48
  • устройство при этом находится в стендбае?
    – Serodv
    13 окт 2017 в 8:52
  • нет, для теста я ей сделал вообще без задержки уведомление, пробовали и с открытым приложением и с свернутым, и с задержкой в минуту, не помогает 13 окт 2017 в 8:57
  • остается только грешить на сервис, андроид может его убить когда и как захочет. Попробуйте устанавливать аларм на ресивер, у него приоритет максимальный, ну и там уже формировать уведомления
    – Serodv
    13 окт 2017 в 9:32
  • Тогда бы поидее вообще не сработало бы ничего, а так что-то происходит, экран блымкает, активити тушится, как буд-то ошибка какая, я вот думаю может я не правильно как то с нотификациями себя веду? Вот этот момент Notification notification = intent.getParcelableExtra(MainBaseService.NOTIFICATION); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); if (notification!=null) notificationManager.notify(requestCode, notification); 13 окт 2017 в 9:46
0

Не знаю почему, но не срабатывал showBackgroundNotification, переделал через

    //  showBackgroundNotification(NOTIFICATION_WATER_ID, notification, null);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(NOTIFICATION_WATER_ID, notification);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.