Android Studio App开发之通知渠道NotificationChannel及给华为、小米手机桌面应用添加消息数量角标实战(包括消息重要级别的设置 附源码)

简介: Android Studio App开发之通知渠道NotificationChannel及给华为、小米手机桌面应用添加消息数量角标实战(包括消息重要级别的设置 附源码)

需要全部源码或运行有问题请点赞关注收藏后评论区留言~~~

一、通知渠道NtoificationChannel

为了分清消息通知的轻重缓急,Android8.0新增了通知渠道,并且必须指定通知渠道才能正常推送消息,一个应用允许拥有多个通知渠道,每个渠道的重要性各不相同,有的渠道消息在通知栏被折叠成小行,有的渠道消息在通知栏展示完整的大行,有的会发出铃声甚至震动等等

效果如下 可以输入标题和内容,然后下拉框里面选择消息的重要级别,根据重要级别的不同消息会有不同的通知方式(这里要连接真机才能具体展示 读者可自行连接 或者参考我之前的博客连接步骤)

代码如下

Java类

package com.example.chapter11;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter11.util.NotifyUtil;
import com.example.chapter11.util.ViewUtil;
public class NotifyChannelActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_title;
    private EditText et_message;
    private String mChannelId = "0"; // 通知渠道的编号
    private String mChannelName; // 通知渠道的名称
    private int mImportance; // 通知渠道的级别
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify_channel);
        et_title = findViewById(R.id.et_title);
        et_message = findViewById(R.id.et_message);
        findViewById(R.id.btn_send_channel).setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            initImportanceSpinner(); // 初始化渠道级别的下拉框
        }
    }
    // 初始化渠道级别的下拉框
    private void initImportanceSpinner() {
        findViewById(R.id.ll_channel).setVisibility(View.VISIBLE);
        ArrayAdapter<String> importanceAdapter = new ArrayAdapter<String>(this,
                R.layout.item_select, importanceDescArray);
        Spinner sp_importance = findViewById(R.id.sp_importance);
        sp_importance.setPrompt("请选择渠道级别");
        sp_importance.setAdapter(importanceAdapter);
        sp_importance.setSelection(3);
        sp_importance.setOnItemSelectedListener(new TypeSelectedListener());
    }
    private int[] importanceTypeArray = {NotificationManager.IMPORTANCE_NONE,
            NotificationManager.IMPORTANCE_MIN,
            NotificationManager.IMPORTANCE_LOW,
            NotificationManager.IMPORTANCE_DEFAULT,
            NotificationManager.IMPORTANCE_HIGH,
            NotificationManager.IMPORTANCE_MAX};
    private String[] importanceDescArray = {"不重要", // 无通知
            "最小级别", // 通知栏折叠,无提示声音,无锁屏通知
            "有点重要", // 通知栏展开,无提示声音,有锁屏通知
            "一般重要", // 通知栏展开,有提示声音,有锁屏通知
            "非常重要", // 通知栏展开,有提示声音,有锁屏通知,在屏幕顶部短暂悬浮(有的手机需要在设置页面开启横幅)
            "最高级别" // 通知栏展开,有提示声音,有锁屏通知,在屏幕顶部短暂悬浮(有的手机需要在设置页面开启横幅)
    };
    class TypeSelectedListener implements AdapterView.OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            mImportance = importanceTypeArray[arg2];
            mChannelId = "" + arg2;
            mChannelName = importanceDescArray[arg2];
        }
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }
    // 发送指定渠道的通知消息(包括消息标题和消息内容)
    private void sendChannelNotify(String title, String message) {
        // 创建一个跳转到活动页面的意图
        Intent clickIntent = new Intent(this, MainActivity.class);
        // 创建一个用于页面跳转的延迟意图
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                R.string.app_name, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // 创建一个通知消息的建造器
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0开始必须给每个通知分配对应的渠道
            builder = new Notification.Builder(this, mChannelId);
        }
        builder.setContentIntent(contentIntent) // 设置内容的点击意图
                .setAutoCancel(true) // 点击通知栏后是否自动清除该通知
                .setSmallIcon(R.mipmap.ic_launcher) // 设置应用名称左边的小图标
                .setContentTitle(title) // 设置通知栏里面的标题文本
                .setContentText(message); // 设置通知栏里面的内容文本
        Notification notify = builder.build(); // 根据通知建造器构建一个通知对象
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotifyUtil.createNotifyChannel(this, mChannelId, mChannelName, mImportance);
        }
        // 从系统服务中获取通知管理器
        NotificationManager notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 使用通知管理器推送通知,然后在手机的通知栏就会看到该消息,多条通知需要指定不同的通知编号
        notifyMgr.notify(Integer.parseInt(mChannelId), notify);
        if (mImportance != NotificationManager.IMPORTANCE_NONE) {
            Toast.makeText(this, "已发送渠道消息", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_send_channel) {
            ViewUtil.hideOneInputMethod(this, et_message); // 隐藏输入法软键盘
            if (TextUtils.isEmpty(et_title.getText())) {
                Toast.makeText(this, "请填写消息标题", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(et_message.getText())) {
                Toast.makeText(this, "请填写消息内容", Toast.LENGTH_SHORT).show();
                return;
            }
            // 发送指定渠道的通知消息(包括消息标题和消息内容)
            sendChannelNotify(et_title.getText().toString(), et_message.getText().toString());
        }
    }
}

XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="消息标题:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_title"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:background="@drawable/editext_selector"
            android:hint="请填写消息标题"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="消息内容:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_message"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="top"
            android:layout_margin="5dp"
            android:background="@drawable/editext_selector"
            android:hint="请填写消息内容"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/ll_channel"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:visibility="gone">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="渠道级别:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <Spinner
            android:id="@+id/sp_importance"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:gravity="center"
            android:spinnerMode="dialog" />
    </LinearLayout>
    <Button
        android:id="@+id/btn_send_channel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="发送渠道消息"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

二、给桌面应用添加信息角标(以华为和小米为例)

每个应用都可以给用户发送很多消息,通知栏显然有时候不够容纳如此之多的消息,于是各应用希望向用户展现未读消息的数量,好让用户知晓有没有未读消息或者是有几条未读消息。例如微信的99+,几个小红点好有申请之类。

因为各手机厂商对消息角标的实现方案各不相同,因此只能给它们的手机分别适配处理,

下面依次介绍华为和小米系手机的适配编码

华为的消息角标不依赖通知推送,允许单独设置红点的展示情况

小米的消息角标方案则依赖于通知推送,必须在发送通知之时一起传送消息数量参数

效果如下 可自行设置

代码如下

Java类

package com.example.chapter11;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter11.util.NotifyUtil;
import com.example.chapter11.util.ViewUtil;
public class NotifyMarkerActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_title;
    private EditText et_message;
    private EditText et_count;
    private static String mChannelId = "3"; // 通知渠道的编号
    private static String mChannelName = "一般重要"; // 通知渠道的名称
    private static int mImportance = NotificationManager.IMPORTANCE_DEFAULT; // 通知渠道的级别
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify_marker);
        et_title = findViewById(R.id.et_title);
        et_message = findViewById(R.id.et_message);
        et_count = findViewById(R.id.et_count);
        findViewById(R.id.btn_show_marker).setOnClickListener(this);
        findViewById(R.id.btn_clear_marker).setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        ViewUtil.hideOneInputMethod(this, et_message); // 隐藏输入法软键盘
        if (TextUtils.isEmpty(et_title.getText())) {
            Toast.makeText(this, "请填写消息标题", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(et_message.getText())) {
            Toast.makeText(this, "请填写消息内容", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(et_count.getText())) {
            Toast.makeText(this, "请填写消息数量", Toast.LENGTH_SHORT).show();
            return;
        }
        String title = et_title.getText().toString();
        String message = et_message.getText().toString();
        int count = Integer.parseInt(et_count.getText().toString());
        if (v.getId() == R.id.btn_show_marker) {
            sendChannelNotify(title, message, count); // 发送指定渠道的通知消息
            Toast.makeText(this, "已显示消息角标,请回到桌面查看", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_clear_marker) {
            sendChannelNotify(title, message, 0); // 发送指定渠道的通知消息
            Toast.makeText(this, "已清除消息角标,请回到桌面查看", Toast.LENGTH_SHORT).show();
        }
    }
    // 发送指定渠道的通知消息(包括消息标题和消息内容)
    private void sendChannelNotify(String title, String message, int count) {
        // 创建一个跳转到活动页面的意图
        Intent clickIntent = new Intent(this, MainActivity.class);
        // 创建一个用于页面跳转的延迟意图
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                R.string.app_name, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // 创建一个通知消息的建造器
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0开始必须给每个通知分配对应的渠道
            builder = new Notification.Builder(this, mChannelId);
        }
        builder.setContentIntent(contentIntent) // 设置内容的点击意图
                .setAutoCancel(true) // 点击通知栏后是否自动清除该通知
                .setSmallIcon(R.mipmap.ic_launcher) // 设置应用名称左边的小图标
                .setContentTitle(title) // 设置通知栏里面的标题文本
                .setContentText(message); // 设置通知栏里面的内容文本
        Notification notify = builder.build(); // 根据通知建造器构建一个通知对象
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotifyUtil.createNotifyChannel(this, mChannelId, mChannelName, mImportance);
        }
        NotifyUtil.showMarkerCount(this, count, notify); // 在桌面的应用图标右上方显示指定数字的消息角标
        // 从系统服务中获取通知管理器
        NotificationManager notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 使用通知管理器推送通知,然后在手机的通知栏就会看到该消息,多条通知需要指定不同的通知编号
        notifyMgr.notify(Integer.parseInt(mChannelId), notify);
    }
}

XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="本页面的消息角标仅支持华为与小米手机"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="消息标题:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_title"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:background="@drawable/editext_selector"
            android:hint="请填写消息标题"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="消息内容:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_message"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="top"
            android:layout_margin="5dp"
            android:background="@drawable/editext_selector"
            android:hint="请填写消息内容"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="消息数量:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/et_count"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:background="@drawable/editext_selector"
            android:gravity="left|center"
            android:inputType="number"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>
    <Button
        android:id="@+id/btn_show_marker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="发送消息同时显示桌面角标"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <Button
        android:id="@+id/btn_clear_marker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="清除应用的消息角标"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

创作不易 觉得有帮助请点赞关注收藏

相关文章
|
10月前
|
Android开发 数据安全/隐私保护
安卓手机修改设备id, 安卓硬改一键新机,手机机型修改(伪装)
提供了完整的设备信息修改功能,包含设备模板配置、基础信息修改、网络信息修改、模拟器检测绕
|
10月前
|
存储 人工智能 文字识别
三款安卓手机word编辑器下载,Microsoft Word,wps office,Word手机版,手机word编辑查看阅读器,PDF转换器apk下载
WPS Office是一款功能强大的办公软件,支持文档编辑、表格处理和演示文稿制作,兼容多种格式并提供丰富的云服务。它具备低内存占用、快速运行的特点,支持跨设备同步与多人协作,内置海量模板及AI辅助功能,如智能写作和PPT自动生成。此外,还可扫描文件、编辑PDF并转换为其他格式,极大提升办公效率,适合手机用户便捷操作。
1133 1
|
12月前
|
XML 搜索推荐 Android开发
Android改变进度条控件progressbar的样式(根据源码修改)
本文介绍了如何基于Android源码自定义ProgressBar样式。首先分析了系统源码中ProgressBar样式的定义,发现其依赖一张旋转图片实现动画效果。接着分两步指导开发者实现自定义:1) 模仿源码创建一个旋转动画XML文件(放置在drawable文件夹),修改图片为自定义样式;2) 在UI控件中通过`indeterminateDrawable`属性应用该动画。最终实现简单且个性化的ProgressBar效果,附带效果图展示。
685 2
|
NoSQL 应用服务中间件 PHP
布谷一对一直播源码android版环境配置流程及功能明细
部署需基于 CentOS 7.9 系统,硬盘不低于 40G,使用宝塔面板安装环境,包括 PHP 7.3(含 Redis、Fileinfo 扩展)、Nginx、MySQL 5.6、Redis 和最新 Composer。Swoole 扩展需按步骤配置。2021.08.05 后部署需将站点目录设为 public 并用 ThinkPHP 伪静态。开发环境建议 Windows 操作系统与最新 Android Studio,基础配置涉及 APP 名称修改、接口域名更换、包名调整及第三方登录分享(如 QQ、微信)的配置,同时需完成阿里云与腾讯云相关设置。
|
Dart 前端开发 Android开发
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
502 4
【09】flutter首页进行了完善-采用android studio 进行真机调试开发-增加了直播间列表和短视频人物列表-增加了用户中心-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
|
Android开发 数据安全/隐私保护 虚拟化
安卓手机远程连接登录Windows服务器教程
安卓手机远程连接登录Windows服务器教程
3840 5
|
安全 搜索推荐 Android开发
Android vs. iOS:解锁智能手机操作系统的奥秘####
【10月更文挑战第21天】 在当今这个数字化时代,智能手机已成为我们生活中不可或缺的伙伴。本文旨在深入浅出地探讨两大主流操作系统——Android与iOS的核心差异、优势及未来趋势,帮助读者更好地理解这两个平台背后的技术哲学和用户体验设计。通过对比分析,揭示它们如何塑造了我们的数字生活方式,并展望未来可能的发展路径。无论您是技术爱好者还是普通用户,这篇文章都将带您走进一个充满创新与可能性的移动世界。 ####
507 3
|
Android开发
android通过代码判断手机是否root
只要/system/bin/su、/system/xbin/su这两个文件中有一个存在,就表明已经具有ROOT权限,如果两个都不存在,则不具有ROOT权限。   // 判断是否具有ROOT权限 public static boolean is_root(){ boo...
5314 0
Android--手机root获取与判断应用是否获取
版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/81075850 import android.
1510 0

热门文章

最新文章