三大消息传递机制区别与联系

目录

总结放开头

1、定义区别:

EventBus

Broadcast Receiver

Notification

2、使用区别:

EventBus

Broadcast Receiver

Notification

3、补充通知渠道:

通知渠道重要程度


总结放开头

BroadCast Receiver:属于安卓全局监听机制,接收系统或应用发出的消息(应用级)

EventBus:应用内各组件间的解耦和消息传递(组件级,如Activity向Service传递信息)

Notification:向用户通知消息(UI界面展示)

1、定义区别:

EventBus

1、发布/订阅事件总线库 - 》“发布-订阅模式”

2、异步分发

3、应用组件间的解耦(不会直接相互引用)与消息传递

4、EventBus适用于任何组件之间的通信,包括Activity、Fragment、Service等

5、实现“一发多收”功能,发送后,多组件都能接受此事件

Broadcast Receiver

1、Android系统全局监听机制,接受来自系统或其他应用的广播消息

2、系统级别事件: 如电池状态,屏幕关闭、电话呼入或网络状态变更等
3、Broadcast Receiver可用于进程间通信、线程间通信以及监听系统的特定事件

Notification

1、UI界面,向用户展示应用状态或信息更新

2、可交互 :通过设置PendingIntent,用户可以通过点击Notification来打开指定的Activity或者执行特定的操作

2、使用区别:

EventBus

核心 :发布事件——订阅事件

依赖

implementation("org.greenrobot:eventbus:3.3.1")

定义事件类(举例)

class ChangeColorEvent(val color:Int) {}

发送事件

 EventBus.getDefault().post(ChangeColorEvent(Color.MAGENTA))

订阅(界面初始化是注册,界面销毁前取消注册)

init {
        //注册EventBus
        EventBus.getDefault().register(this)
    }
 
  override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        //取消EventBus事件订阅
        EventBus.getDefault().unregister(this)
    }
 
@Subscribe(threadMode = ThreadMode.MAIN)
    fun changeColor(event:ChangeColorEvent){
        setTextColor(event.color)
    }

Broadcast Receiver

创建Reciever

class MyBoradCastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
/**
 如下接收外部消息
 */       val action = intent!!.getStringExtra(NotificationHelper.BROADCAST_EXTRA_KEY)
  
    }
}

动态注册(依赖于注册的Activity,只要此Activity关闭,广播也失效

val mReceiver = MyBroadCastReceiver();              
val intentFilter = IntentFilter(NotificationHelper.action_broadcast_notification)
registerReceiver(mReceiver, intentFilter);
 

发送标准广播

sendBoardcast(intent)

接收广播

override fun onReceive(context:Context , intent:Intent ) {
    String data = intent.getStringExtra("key"); // 获取传递的数据
    // 在这里处理接收到的广播 逻辑代码实现
}

取消注册

手动移除广播接收器 ——>在onDestroy()重写中加入unregister(mReceiver)

Notification

(可以自定义通知栏,这里采用系统自带通知栏)

申请权限

Manifest 中 ,application外添加

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val result = checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
            if (result != PackageManager.PERMISSION_GRANTED){ //没有权限
  val launcher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
                    if (it){
                        //申请到权限了
                    }else{
                        //用户拒绝授权
                    }
                 }
                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }

创建NotificationManager

 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

创建通知渠道

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channel_id, channel_name, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

使用Build构造器创建Notification对象

//创建Notification,传入Context和channelId
val notification = new NotificationCompat.Builder(this, "channelId")
                        .setAutoCancel(true)
                        .setContentTitle("收到聊天消息")
                        .setContentText("今天晚上吃什么")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setContentIntent(pendingIntent)
                        //在build()方法之前还可以添加其他方法
                        .build();

显示通知

notificationManager.notify(1, notification);

通知消失

创建Notification时添加setAutoCancel(true) ,或者如下手动取消

//传入对应通知的id
notificationManager.cancel(1);

3、补充通知渠道:

一个应用可以有多个通知权限(如Twitter可以分别设置通知 私信,与你相关推文);

每条通知都要属于一个对应的渠道;

自由选择通知渠道的重要程度(是否响铃、是否振动、或者是否要关闭这个渠道的通知);

通知渠道重要程度

public class NotificationManager {
    ......
    public static final int IMPORTANCE_DEFAULT = 3;
    public static final int IMPORTANCE_HIGH = 4;
    public static final int IMPORTANCE_LOW = 2;
    public static final int IMPORTANCE_MAX = 5;
    public static final int IMPORTANCE_MIN = 1;
    public static final int IMPORTANCE_NONE = 0;
    public static final int IMPORTANCE_UNSPECIFIED = -1000;
 
}

  • 14
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值