EventBus是(框架)系统、应用、控件、线程间发布/订阅事件的第三方框架
首先在gradle文件中添加EventBus的依赖(随着版本改变)
在相关Activity中的onCreat()、onDestory()注册和解注EventBus
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
}
//注册
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
//解绑
事件发布者如何发布事件
EventBus.getDefault().post(实参);
//根据实际根据实际情况传参
全局广播(默认发送的广播,就是全局广播,所有的App都可以请求接受)
发送的广播事件可被其他应用程序获取,也能响应其他应用程序发送的广播事件(可以通过exported–是否监听其他应用程序发送的广播 在清单文件中控制)全局广播既可以动态注册,也可以静态注册。
本地广播( 本地广播只能动态注册,不能静态注册。)
发送的广播事件不被其他应用程序获取,也不能响应其他应用程序发送的广播事件。动态注册或方法时需要用到LocalBroadcastManager。
public void aaa(View view) {
Intent intent=new Intent();
intent.setAction("com.bw.local");
localBroadcastManager.sendBroadcast(intent);
}
public class MyLocal extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.bw.local")){
Toast.makeText(context,"本地广播",Toast.LENGTH_SHORT).show();
}
}
}
BroadCastReceiver实现消息传递
public void bbb(View view) {
NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.item);
remoteViews.setTextViewText(R.id.tv1,"nihao");
remoteViews.setTextViewText(R.id.tv2,"nihaobuhao");
remoteViews.setImageViewResource(R.id.iv,R.drawable.ic_launcher_background);
Intent intent=new Intent();
intent.setAction("com.bw.pre");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,101,intent,PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.iv,pendingIntent);
Notification.Builder builder=new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pendingIntent).setCustomContentView(remoteViews);
Notification notification=builder.build();
notificationManager.notify(1,notification);
}
MyLocal myLocal=new MyLocal();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.bw.local");
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(myLocal,intentFilter);
MyBroadReceiver myBroadReceiver=new MyBroadReceiver();
intentFilter.addAction("com.bw.pre");
registerReceiver(myBroadReceiver,intentFilter);
public class MyLocal extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("com.bw.local")){
Toast.makeText(context,"本地广播",Toast.LENGTH_SHORT).show();
}
}
}