Подтвердить что ты не робот

LocalNotification с AlarmManager и BroadcastReceiver не запускается в Android O (oreo)

У меня есть локальные уведомления, работающие на Android до SDK 26

Но в Android O я получил следующее предупреждение, и широковещательный приемник не срабатывает.

W/BroadcastQueue: Background execution not allowed: receiving Intent { act=package.name.action.LOCAL_NOTIFICATION cat=[com.category.LocalNotification] flg=0x14 (has extras) } to package.name/com.category.localnotifications.LocalNotificationReceiver

Из того, что я читал, приемники вещания более ограничены в Android O, но если это так, как мне планировать вещание, если я хочу, чтобы оно запускалось, даже если основное действие не запущено?

Должен ли я использовать услуги вместо получателей?

Это код запуска AlarmManager:

public void Schedule(String aID, String aTitle, String aBody, int aNotificationCode, long aEpochTime)
{
    Bundle lExtras = new Bundle();
    lExtras.putInt("icon", f.getDefaultIcon());
    lExtras.putString("title", aTitle);
    lExtras.putString("message", aBody);
    lExtras.putString("id", aID);
    lExtras.putInt("requestcode", aNotificationCode);

    Intent lIntent = 
      new Intent(LocalNotificationScheduler.ACTION_NAME)
      .addCategory(NotificationsUtils.LocalNotifCategory)
      .putExtras(lExtras);

    PendingIntent lPendIntent = PendingIntent.getBroadcast(f.getApplicationContext(), aNotificationCode,
                                                           lIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager lAlarmMgr = (AlarmManager) f.getSystemService(Context.ALARM_SERVICE);
    lAlarmMgr.set(AlarmManager.RTC, 1000, lPendIntent);
}

Это код получателя:

public class LocalNotificationReceiver extends BroadcastReceiver {

public static native void   nativeReceiveLocalNotification (String aID, String aTitle, String aMessage, boolean aOnForeground );

/** This method receives the alarms set by LocalNotificationScheduler,
*   notifies the CAndroidNotifications c++ class, and (if needed) ships a notification banner 
*/
@Override
public void onReceive(Context aContext, Intent aIntent)
{
    Toast.makeText(context, text, duration).show();
}

}

Android манифест:

<receiver android:name="com.category.localnotifications.LocalNotificationReceiver">
        <intent-filter>
            <action android:name="${applicationId}.action.LOCAL_NOTIFICATION" />
            <category android:name="com.category.LocalNotification" />
        </intent-filter>
    </receiver>
4b9b3361

Ответ 1

Android O довольно новы на сегодняшний день. Поэтому я стараюсь переварить и предоставить максимально точную информацию.

С https://developer.android.com/about/versions/oreo/background.html#broadcasts

  • Приложения, предназначенные для Android 8.0 или выше, больше не могут регистрировать приемники широковещания для неявных широковещательных рассылок в своем манифесте.
    • Приложения могут использовать Context.registerReceiver() во время выполнения, чтобы зарегистрировать получателя для любой передачи, неявной или явной.
  • Приложения могут продолжать регистрировать явные трансляции в своем манифесте.

Кроме того, в https://developer.android.com/training/scheduling/alarms.html примеры используют явную трансляцию и не упоминают ничего особенного в отношении Android O.


Могу ли я предложить вам попробовать явную трансляцию следующим образом?

public static void startAlarmBroadcastReceiver(Context context, long delay) {
    Intent _intent = new Intent(context, AlarmBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, _intent, 0);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    // Remove any previous pending intent.
    alarmManager.cancel(pendingIntent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);        
}

AlarmBroadcastReceiver

public class AlarmBroadcastReceiver extends BroadcastReceiver {


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

}

В AndroidManifest просто определите класс как

<receiver android:name="org.yccheok.AlarmBroadcastReceiver" >
</receiver>

Ответ 2

Сегодня у меня была такая же проблема, и мое уведомление не работало. Я думал, что менеджер аварийных сигналов не работает в Oreo, но проблема была с уведомлением. В Oreo нам нужно добавить Channel id. Пожалуйста, взгляните на мой новый код:

int notifyID = 1; 
String CHANNEL_ID = "your_name";// The id of the channel. 
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(HomeActivity.this)
            .setContentTitle("Your title")
            .setContentText("Your message")
            .setSmallIcon(R.drawable.notification)
            .setChannelId(CHANNEL_ID)
            .build();

Проверьте это решение. Это сработало как шарм.

fooobar.com/questions/177244/...

Я показываю мой метод:

public static void pendingListNotification(Context context, String totalCount) {
        String CHANNEL_ID = "your_name";// The id of the channel.
        CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationCompat.Builder mBuilder;

        Intent notificationIntent = new Intent(context, HomeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.PENDING_NOTIFICATION, AppConstant.TRUE);//PENDING_NOTIFICATION TRUE
        notificationIntent.putExtras(bundle);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= 26) {
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            mNotificationManager.createNotificationChannel(mChannel);
            mBuilder = new NotificationCompat.Builder(context)
//                .setContentText("4")
                    .setSmallIcon(R.mipmap.logo)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setLights(Color.RED, 300, 300)
                    .setChannelId(CHANNEL_ID)
                    .setContentTitle(context.getResources().getString(R.string.yankee));
        } else {
            mBuilder = new NotificationCompat.Builder(context)
//                .setContentText("4")
                    .setSmallIcon(R.mipmap.logo)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setLights(Color.RED, 300, 300)
                    .setContentTitle(context.getResources().getString(R.string.yankee));
        }

        mBuilder.setContentIntent(contentIntent);

        int defaults = 0;
        defaults = defaults | Notification.DEFAULT_LIGHTS;
        defaults = defaults | Notification.DEFAULT_VIBRATE;
        defaults = defaults | Notification.DEFAULT_SOUND;

        mBuilder.setDefaults(defaults);
        mBuilder.setContentText(context.getResources().getString(R.string.you_have) + " " + totalCount + " " + context.getResources().getString(R.string.new_pending_delivery));//You have new pending delivery.
        mBuilder.setAutoCancel(true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

Ответ 3

Создайте AlarmManager, указав явное намерение (явно определите имя класса широковещательного приемника):

private static PendingIntent getReminderReceiverIntent(Context context) {
    Intent intent = new Intent("your_package_name.ReminderReceiver");
    // create an explicit intent by defining a class
    intent.setClass(context, ReminderReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return pendingIntent;
}

Также не забудьте создать канал уведомлений для Android Oreo (API 26) при создании фактического уведомления:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (VERSION.SDK_INT >= VERSION_CODES.O) {
    notificationManager.createNotificationChannel(NotificationFactory.createNotificationChannel(context));
} else {
    notificationManager.notify(NotificationsHelper.NOTIFICATION_ID_REMINDER, notificationBuilder.build());
}

Ответ 4

попробуйте этот код для Android O 8.1

Intent nIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
        nIntent.addCategory("android.intent.category.DEFAULT");
        nIntent.putExtra("message", "test");
        nIntent.setClass(this, AlarmReceiver.class);

PendingIntent broadcast = PendingIntent.getBroadcast(getAppContext(), 100, nIntent, PendingIntent.FLAG_UPDATE_CURRENT);