一、广播类型
Android中广播分为标准广播和有序广播。
Normal broadcasts
ordered broadcasts
标准广播异步执行,所有广播接收器几乎同一时刻接受到广播消息,它们之间没有先后顺序,无法被截断
有序广播同步执行,同一时刻只有一个广播接收器能够接收到发出的广播消息,优先级高的广播接收器会先接收到广播消息,前面的广播接收器能截断正在传递的广播。
二、广播接收器的注册
动态注册:即在代码中注册
例:
package com.example.somedemos;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkChangeReceiver,intentFilter);
}
protected void onDestroy() {
super.onDestroy();
//注销广播接收器
unregisterReceiver(networkChangeReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isAvailable()){
Toast.makeText(context,"network is available",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"network is unavailable",Toast.LENGTH_LONG).show();
}
}
}
}
动态注册必须在程序启动后才能接受到广播,因为注册的逻辑是写在onCreate()方法中的,而静态注册可以让程序在未启动的情况下就能接收到广播。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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.SomeDemos"
tools:targetApi="31">
<!-- 注册器写在application标签后 !-->
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
三、广播的最佳实践
实现强制下线功能:
总是有些bug…跑通了再把代码放上来