[Android] Notification和广播的简单使用

举报
开心星人 发表于 2022/06/29 17:19:38 2022/06/29
【摘要】 @toc 🌳效果展示点击发送广播,会弹出通知点击清除通知图标会删除通知 🌳分析动态注册广播接收器 MyReceiver myReceiver=new MyReceiver(); IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("cn.edu.henu.sendMessage"); //这个Acti...

@toc


🌳效果展示

在这里插入图片描述
点击发送广播,会弹出通知
在这里插入图片描述
点击清除通知图标会删除通知


🌳分析

动态注册广播接收器

 MyReceiver myReceiver=new MyReceiver();
 IntentFilter intentFilter=new IntentFilter();
 intentFilter.addAction("cn.edu.henu.sendMessage"); 
 //这个Action自己选择一个字符串,最好带上包名,不容易重复
 registerReceiver(myReceiver,intentFilter);

intent发送广播

Intent intent=new Intent("cn.edu.henu.sendMessage");
//这里的action要和注册广播接收器那里的action一致
intent.putExtra("info","动态注册");
sendBroadcast(intent);

广播接收器接收到广播后,自动调用MyReceiver的OnReceive方法
在该方法中写弹出通知的逻辑代码

//        创建NotificationManager
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        String channelID = "my_channel_ID";
        String channelNAME = "my_channel_NAME";
        int level = NotificationManager.IMPORTANCE_HIGH;
//            8.0以上必须先创建通道
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context, channelID)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Notification")
                        .setContentText("我是通知")
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setAutoCancel(true);
        manager.notify(101, builder.build());

删除通知

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(101);
//注意上面notify的时候id也是101

🌳全部代码

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button send;
    private Button clear;
    public Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyReceiver myReceiver=new MyReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("cn.edu.henu.sendMessage");
        registerReceiver(myReceiver,intentFilter);

        send=findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent("cn.edu.henu.sendMessage");
                intent.putExtra("info","动态注册");
                sendBroadcast(intent);
            }
        });

        clear=findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(101);
            }
        });
    }

}

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "MyReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String msg=intent.getStringExtra("info");
        Toast.makeText(context,msg,Toast.LENGTH_LONG).show();

//        创建NotificationManager
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        String channelID = "my_channel_ID";
        String channelNAME = "my_channel_NAME";
        int level = NotificationManager.IMPORTANCE_HIGH;
//            8.0以上必须先创建通道
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context, channelID)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("Notification")
                        .setContentText("2012080097_张开斌")
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setAutoCancel(true);
        manager.notify(101, builder.build());

    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

   <Button
       android:id="@+id/send"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="发送广播消息"
       />
    <Button
        android:id="@+id/clear"
        android:text="清除通知图标"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。