目录
BroadcastReceiver广播
BroadcastReceiver为Android的四大组件之一。使用广播接受器并注册应用感兴趣的广播,应用就可以接受到来自系统或其他应用的广播。
目录
BroadcastReceiver广播
一、广播的分类
二、注册广播
动态注册:
静态注册
发送广播
MainActivity布局文件:
发送有序广播
//发送本地广播
一、广播的分类
目录
BroadcastReceiver广播
一、广播的分类
二、注册广播
动态注册:
静态注册
发送广播
MainActivity布局文件:
发送有序广播
//发送本地广播
标准广播:在广播发出之后,所有的广播接收器几乎都会在同一时刻接收到这条广播消息,它们之间没有任何先后顺序可言。这种广播的效率会比较高,但同时也意味着它是无法被截断的。
有序广播:可以在注册广播接受器时设置优先级,这样在广播发送后,优先级高的广播接受器会先收到广播,等优先级高的广播接受器处理晚后,优先级低的广播才能接受到。在处理广播时可以截断广播,这样后面的广播接受器也就收不到这条广播了。
接收广播
想要接受广播首先要编写广播接受器,编写广播接受器要继承BroadcastReceiver并重写onReceive()方法,当广播接受器接收到广播后,就会调用这个方法。
编写一个监听网络状态变化的广播接受器,当网络发生变化时就会进行提示:
public class NetworkStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Network changed.", Toast.LENGTH_SHORT).show();
}
}
二、注册广播
注册广播有动态注册和静态注册两种。动态注册是使用代码注册,静态注册是在AndroidManifast.xml中注册,动态注册相对来说更加灵活,但是采用这种方式注册的广播只有在应用运行后才能接收到广播。如果想在应用还未启动就接受广播,此时就需要采用静态注册。
动态注册:
public class MainActivity extends AppCompatActivity {
private NetworkStateReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
receiver = new NetworkStateReceiver();
registerReceiver(receiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}CONNECTIVITY_CHANGE
}
静态注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Learning"
tools:targetApi="31" >
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".NetworkStateReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
三、发送广播
先注册一个广播接受器:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received MyBroacast.", Toast.LENGTH_SHORT).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Learning"
tools:targetApi="31" >
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.example.learning.MY_BROADCAST" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/send_broadcast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Broadcast"/>
</LinearLayout>
MainActivity,使用sendBroadcast()发送广播:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendBroadcast = findViewById(R.id.send_broadcast);
sendBroadcast.setOnClickListener(view->{
Intent intent = new Intent("com.example.learning.MY_BROADCAST");
intent.setPackage("com.example.learning");
sendBroadcast(intent);
});
}
}
android 8.0以后版本对静态注册的广播做了限制,自定义的接收器会接收不到发送方发送的广播。发送方需要在intent中设定接收方的package,接收方才会接收到intent.setPackage("com.example.learning");。
发送有序广播
注册广播接受器MySecondBroadcastReceiver,并给两个广播接受器设置priority
rpublic class MySecondBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MySecondBroadcastReceiver received MyBroadcast.", Toast.LENGTH_SHORT).show();
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Learning"
tools:targetApi="31" >
<activity
android:name=".MainActivity"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="10">
<action android:name="com.example.learning.MY_BROADCAST" />
</intent-filter>
</receiver>
<receive
android:name=".MySecondBroadcastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="5">
<action android:name="com.example.learning.MY_BROADCAST" />
</intent-filter>
</receiver>
</application>
</manifest>
使用sendOrderedBroadcast()发送有序广播,第二个参数为接收权限,这里指定为null。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendBroadcast = findViewById(R.id.send_broadcast);
sendBroadcast.setOnClickListener(view->{
Intent intent = new Intent("com.example.learning.MY_BROADCAST");
intent.setPackage("com.example.learning");
sendOrderedBroadcast(intent, null);
});
}
}
这时候MyBroadcastReceiver会首先接收到广播,等MyBroadcastReceiver处理完后,MySecondBroadcastReceiver才会接收到广播。
在处理广播时可以使用abortBroadcast();截断广播。
发送本地广播
使用本地广播机制只能够在应用程序的内部进行传递,并且广播接收器也只能接收来自本应用程序发出的广播。引入这一机制是为了防止在发送携带关键性数据的广播时被其他应用截获,以及防止其他应用不停的向我们的广播接受器发送垃圾广播。
本地广播主要由LocalBroadcastManager进行管理,它提供了注册本地广播监听器,以及发送本地广播的方法
//获取实例
LocalBroadcastManager.getInstance(context);
//注册本地广播
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
//注销本地广播
localBroadcastManager.unRegisterReceiver(localReceiver);
//发送本地广播
localBroadcastManager.sendBroadcast(intent);
public class MainActivity extends AppCompatActivity {
private MyBroadcastReceiver myBroadcastReceiver;
private LocalBroadcastManager localBroadcastManagerl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendBroadcast = findViewById(R.id.send_broadcast);
myBroadcastReceiver = new MyBroadcastReceiver();
localBroadcastManagerl = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter("com.example.learning.MY_BROADCAST");
localBroadcastManagerl.registerReceiver(myBroadcastReceiver, intentFilter);
sendBroadcast.setOnClickListener(view->{
Intent intent = new Intent("com.example.learning.MY_BROADCAST");
localBroadcastManagerl.sendBroadcast(intent);
});
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManagerl.unregisterReceiver(myBroadcastReceiver);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MyBroadcastReceiver received MyBroadcast.", Toast.LENGTH_SHORT).show();
}
}
}