BroadCastReceiver
什么是BroadcastReceiver ?
BroadcastReceiver是广播接收者安卓四大组件之一,应用于同一APP下多个组件之间传递数据(Activity/Fragment/Service之间传递数据)或两个APP之间传递数据
BroadcastReceiver三要素
广播三要素:
(1)广播发送者 : 发送广播
(2)广播接收者(调频): 用于接收广播
(3)要处理的事情 :处理广播的相关信息, Intent有图对象
广播的生命周期&注册方式
静态注册和动态注册的区别:假如说Activity是接受者:
动态注册:
(1)广播会跟Activity的生命周期的结束而结束;
(2)自由的控制注册和取消,有很大的灵活性
//创建一个广播
myReceiver = new MyReceiver();
//添加广播过滤器
IntentFilter intentFilter = new IntentFilter();
//添加action
intentFilter.addAction(BroadcastConst.ACTION);
//注册
registerReceiver(myReceiver,intentFilter);
静态注册:
(1)广播不会跟随Activity的生命周期的结束而结束,一直存在,即使应用程序关闭,也会被唤醒接受广播
(2)全局的广播
在清单文件中注册
<!--我是一个广播-->
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.feng.broad"></action>
</intent-filter>
</receiver>
<!--广播结束-->
广播的类型
无序广播(标准广播)
Intent intent = new Intent();
intent.setAction("com.feng.broad");
Bundle bundle = new Bundle();
bundle.putString("msg","大风起兮云飞扬,高薪就业创辉煌");
intent.putExtras(bundle);
sendBroadcast(intent);
有序广播
Intent intent1 = new Intent();
intent1.setAction("com.feng.broad");
//第一个参数是intent 二是权限名.
sendOrderedBroadcast(intent1,null);
使用步骤
1.写一个MyReceiver类继承BroadcastReceiver
2.清单文件中注册并设置过滤器
3.广播者发送广播
4.广播接收者判断Action 接收数据
演示案例代码
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.day12">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name=".MyReceiver2"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="com.feng.broad"></action>
</intent-filter>
</receiver>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="900">
<action android:name="com.feng.broad" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button sendId;
private MyReceiver myReceiver;
private Button sendOrderId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendOrderId = findViewById(R.id.send_order_id);
sendOrderId.setOnClickListener(this);
sendId = findViewById(R.id.send_id);
sendId.setOnClickListener(this);
//1,创建一个广播
// myReceiver = new MyReceiver();
// //添加广播过滤器
// IntentFilter intentFilter = new IntentFilter();
// //添加action
// intentFilter.addAction(BroadcastConst.ACTION);
// //注册
// registerReceiver(myReceiver,intentFilter);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.send_id:
Intent intent = new Intent();
intent.setAction("com.feng.broad");
Bundle bundle = new Bundle();
bundle.putInt("msg",123);
intent.putExtras(bundle);
sendBroadcast(intent);
break;
case R.id.send_order_id:
Intent intent1 = new Intent();
intent1.setAction("com.feng.broad");
sendOrderedBroadcast(intent1,null);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//注销广播
unregisterReceiver(myReceiver);
}
}
广播接收者
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//TODO 1:获取action
String action = intent.getAction();
if(BroadcastConst.ACTION.equals(action)){
// Bundle extras = intent.getExtras();
// int msg = extras.getInt("msg");
Log.i(TAG, "onReceive: ");
}
}
}
本地广播
简介:
发送的广播事件不被其他应用程序获取,也不能响应其他应用程序发送的广播事件,并且只能使用LocalBroadcastManager通过动态注册
PS:androidx需导入以下包才可以正常使用LocalBroadcastManager类
`implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'`
特点:
可以明确的知道正在发送的广播不会离开我们的程序,不用担心机密数据泄露
其他程序无法将广播发送到我们的程序内部,不需要担心安全问题
发送本地广播比系统全局的广播效率高
代码
//创建一个本地广播
localBroadcastManager = LocalBroadcastManager.getInstance(this);
//动态注册一个广播
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.feng");
localBroadcastManager.registerReceiver(myReceiver,intentFilter);46
全局广播
简介:
发送的广播事件可被其他应用程序获取,也能响应其他应用程序发送的广播事件(可以通过 exported–是否监听其他应用程序发送的广播 在清单文件中控制) 全局广播既可以动态注册,也可以静态注册
接收系统消息的广播
只需要在清单文件中声明相应的系统Action 即可实现对系统动作的广播
案例:使用BroadCastReceiver发送消息更新UI
清单
<?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"
android:orientation="vertical"
tools:context=".Main2Activity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/updata_ui_id"
android:text="更新一个图片"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_id"
android:src="@mipmap/ic_launcher"
/>
</LinearLayout>
接收者
public class MyReceiver2 extends BroadcastReceiver {
private Handler handler;
private ImageView imageView;
public MyReceiver2(Handler handler, ImageView imageView) {
super();
this.handler = handler;
this.imageView = imageView;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.feng.ui".equals(action)){
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageResource(R.mipmap.ic_launcher_round);
}
});
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private Button updataUiId;
private ImageView imageId;
private MyReceiver2 myReceiver2;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updataUiId = findViewById(R.id.updata_ui_id);
imageId = findViewById(R.id.image_id);
myReceiver2 = new MyReceiver2(handler,imageId);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.feng.ui");
registerReceiver(myReceiver2,intentFilter);
updataUiId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("com.feng.ui");
sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver2);
}
}
EventBus
三个角色
Event:事件,它可以是任意类型,EventBus会根据事件类型进行全局的通知。
Subscriber:事件订阅者,在EventBus 3.0之前我们必须定义以onEvent开头的那几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe,并且指定线程模型,默认是POSTING。
Publisher:事件的发布者,可以在任意线程里发布事件。一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。
四种线程模型
EventBus3.0有四种线程模型,分别是:
POSTING:默认,表示事件处理函数的线程跟发布事件的线程在同一个线程。
MAIN:表示事件处理函数的线程在主线程(UI)线程,因此在这里不能进行耗时操作。
BACKGROUND:表示事件处理函数的线程在后台线程,因此不能进行UI操作。如果发布事件的线程是主线程(UI线程),那么事件处理函数将会开启一个后台线程,如果果发布事件的线程是在后台线程,那么事件处理函数就使用该线程。
ASYNC:表示无论事件发布的线程是哪一个,事件处理函数始终会新建一个子线程运行,同样不能进行UI操作。
依赖导包(Androidx)
implementation 'org.greenrobot:eventbus:3.0.0'
用fragment接收eventbus代码
fragment
public class BlankFragment extends Fragment {
private TextView show;
public BlankFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflate = inflater.inflate(R.layout.fragment_blank, container, false);
show = inflate.findViewById(R.id.show);
return inflate;
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void getmsg(Message msg) {
String msg1 = msg.getMsg();
show.setText(msg1);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().removeAllStickyEvents();
}
}
MainActivity
public class EvevtBus extends AppCompatActivity {
private EditText edit;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_evevt_bus);
edit = (EditText) findViewById(R.id.edit);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String msg = edit.getText().toString();
Message message = new Message(msg);
EventBus.getDefault().post(message);
}
});
}
}
Banner
依赖&权限
导入依赖
compile 'com.youth.banner:banner:1.4.10'
清单文件权限
<!-- if you want to load images from the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- if you want to load images from a file OR from the internet -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
案例代码
XML:
<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=".Bunner">
<com.youth.banner.Banner
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.youth.banner.Banner>
</LinearLayout>
外部类图片下载器
public class imgLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bunner);
banner = (Banner) findViewById(R.id.banner);
//绑定下载器
banner.setImageLoader(new imgLoader());
//创建图片集合作为数据源
ArrayList<String> list = new ArrayList<>();
list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571309316416&di=b25fb8a2fee660ae963a41c56c067cc6&imgtype=0&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F49c607dbba21551282e97ac4c71294373b4a488e.jpg");
list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571309316412&di=f8e4ac3d1788a1419a961d169eac8504&imgtype=0&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2Fc4f07739f34bc111ee50c84b2780a49d850b9cd5.jpg");
list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571309316410&di=71bed840c95a5bd8a9dc4899526981bb&imgtype=0&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farchive%2Fc65f0fb7343516425d1b0750094c111175a4cfb4.jpg");
list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571309316406&di=ed83b7a2eb9c9d5ab90ed112d4912bd4&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F0%2F58a3c9d34cf61.jpg");
banner.setImages(list);
//设置banner样式
banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
//设置动画效果
banner.setBannerAnimation(Transformer.DepthPage);
//设置轮播间隔时间
banner.setDelayTime(1000);
//启动banner
banner.start();
}
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20191017163241813.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0Nnc2JlYmV0dGVy,size_16,color_FFFFFF,t_70)