Android 8.0版本Broadcast以及Notification

Android 8.0版本Broadcast以及Notification

0.前言

本篇博客主要记录了Android 8.0版本(API 26+)和之前版本的Broadcast和Notification有何不同。

如果想进行更深入的相关知识探究,可以直接看最后的一部分(参考文献)。

1.Broadcast

Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers.

If your app targets Android 8.0 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that don’t target your app specifically). You can still use a context-registered receiver when the user is actively using your app.

安卓官方说明从8.0之后,不再接受不确定具体目标的广播(为了节省手机资源)。所以要使用上下文注册的BroadCast。

解决方案:(有的时候要在getPackageName()前加this.)

ComponentName componentName = new ComponentName(getPackageName(),getPackageName()+".xxxxReceiver");
intent.setComponent(componentName);
sendBroadcast(intent);

2.Notification

Android 8.0后创建notification必须放入channel中

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 = getString(R.string.channel_name);
        String description = 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 = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

android 8.0版本添加notification动作用getActivity(官方不再使用getBroadcast,没有测试是否可以)

// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that will fire when the user taps the notification
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

4.参考文献

notification的官方文档

broadcast的官方文档

api查询官方

你可能感兴趣的:(Android 8.0版本Broadcast以及Notification)