android8.0适配通知和判断通知栏是否开启 搜刮拼凑来的代码,只当是记录

该博客主要记录了 Android 8.0 系统下通知适配以及通知栏开启的相关内容,虽代码是拼凑而来,但可作为相关技术操作的记录参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    boolean notificationEnabled = isNotificationEnabled(this);
    
    //判断是否开启通知
    if (!notificationEnabled) {
        gotoSet();
    } else {  //通知信息
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        ;
        String CHANNEL_ID = "main";//唯一标识
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "聊天信息"
                    , NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("网吧");
        builder.setContentText("我是你的霸王");
        //以上三个必须写,否则报错,下面这个RemoteViews 是自定义布局
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
        remoteViews.setTextViewText(R.id.notifition_content, "李金才无敌了");
        remoteViews.setTextViewText(R.id.notifition_title, "李金才");
        remoteViews.setImageViewResource(R.id.notifition_pic, R.drawable.loading_01);
        builder.setContent(remoteViews);
        notificationManager.notify(2, builder.build());
    }



    //判断是否开启通知栏
    
 private boolean isNotificationEnabled(Context context) {
    boolean isOpened = false;
    try {
        isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
    } catch (Exception e) {
        e.printStackTrace();
        isOpened = false;
    }
    return isOpened;

}



//跳转到通知栏页面

private void gotoSet() {
    Intent intent = new Intent();
    if (Build.VERSION.SDK_INT >= 26) {
        // android 8.0引导
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
    } else if (Build.VERSION.SDK_INT >= 21) {
        // android 5.0-7.0
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("app_package", getPackageName());
        intent.putExtra("app_uid", getApplicationInfo().uid);
    } else {
        // 其他
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts("package", getPackageName(), null));
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值