广播
1 接收系统广播
1.1 动态注册
动态注册广播接收器很灵活,但是必须在启动程序后才能接收到广播.
接收网络变化广播实例
mainActivity设置广播接收器
//要接收的内容
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");
networkChangeReceiver = new NetworkChangeReceiver();
//注册接收器
registerReceiver(networkChangeReceiver,intentFilter);
}
//继承广播接收器
private class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();
//系统服务类
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
//网络实例
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
//判断是否有网络
if (networkInfo != null && networkInfo.isAvailable()){
Toast.makeText(context,"network is avaiable",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"network is unavailable",Toast.LENGTH_SHORT).show();
}
}
}
AndroidMainfest.xml中注册监听网络变化的权限
<!--在manifest标签下-->
<!-- 监听网络变化的权限-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1.2 静态注册
在new中选择other,再选择Broadcast Receiver.
Exported属性表示是否允许这个广播接收器接收本程序以外的广播,
Enabled属性表示是否启用这个广播接收器.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context,"Boot Complet",Toast.LENGTH_SHORT).show();
// throw new UnsupportedOperationException("Not yet implemented");
}
}
AndroidMainfest.xml 中注册监听网络变化的权限
<!-- 监听开机的权限-->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
AndroidMainfest.xml 中设置接收器的接收内容
<!--application下-->
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<!-- 接收广播的内容(开机) -->
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
2 发送自定义广播
静态注册接收器现在有严格规定
所以,得动态注册接收器接收自定义广播
1.在MainActivity中动态注册接收器
//动态注册接收器1
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"1",Toast.LENGTH_SHORT).show();
}
};
//动态注册接收器2
private BroadcastReceiver mReceiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"2",Toast.LENGTH_SHORT).show();
}
};
//要接收的广播
private IntentFilter intentFilter;
oncreate(){
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.myapplication.MY_BROADCAST");
//注册接收器
registerReceiver(mReceiver,intentFilter);
registerReceiver(mReceiver2,intentFilter);
}
2.发送广播
//自定义并发送广播
Intent intent = new Intent();
intent.setAction("com.example.myapplication.MY_BROADCAST");
sendBroadcast(intent);
3.将广播发送改成sendOrderedBroadcast方法即可发送有序广播
//自定义并发送广播
Intent intent = new Intent();
intent.setAction("com.example.myapplication.MY_BROADCAST");
sendOrderedBroadcast(intent,null);
abortBroadcast();//可以截断广播
3 使用本地广播
本地广播其他程序接收不到广播.
1.自定义本地广播接收器(内部类)
private class LocalReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"received local ",Toast.LENGTH_SHORT).show();
}
}
2.MainActivity中自定义本地广播并发送
private IntentFilter intentFilter;
//自定义的接收器
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取localBroadcastManager实例对广播进行管理
localBroadcastManager = LocalBroadcastManager.getInstance(this);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送本地广播
Intent intent = new Intent("com.example.myapplication.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
}
});
//要接收的广播
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.myapplication.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
//注册本地广播接收器
localBroadcastManager.registerReceiver(localReceiver,intentFilter);;
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
4 强制下线案例
本案例共两个界面, 登录界面和主界面
思路:
建立BaseActivity,每当activity聚焦时,便注册广播接收器,否则解除注册.继承了该类的活动在被聚焦时都会动态注册广播接收器.
1.活动处理工具ActivityCollector
public class ActivityCollector {
private static List<Activity> activities = new ArrayList<>();
//添加活动
public static void addActivity(Activity activity){
activities.add(activity);
}
//去掉活动
public static void removeActivity(Activity activity){
activities.remove(activity);
}
//销毁所有活动
public static void finishAll(){
for (Activity activity: activities){
if (!activity.isFinishing()){
activity.finish();
}
}
}
}
2.BaseActivity
public class BasicActivity extends AppCompatActivity {
private ForceOfflineReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.myapplication.FORCE_OFFLINE");
receiver= new ForceOfflineReceiver();
//注册接收器
registerReceiver(receiver,intentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (receiver != null){
//解除注册
unregisterReceiver(receiver);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
//自定义广播接收器
private class ForceOfflineReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Warning");
builder.setMessage("You are forced to be offline.Please try to login again.");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//强制下线,删除所有活动,跳转到登录界面
ActivityCollector.finishAll();
Intent intent = new Intent(context,LoginActivity.class);
context.startActivity(intent);
}
});
builder.show();
}
}
}
3.登录界面login.xml(包含账号密码点击按钮)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal"
>
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="Account:"
/>
<EditText
android:id="@+id/account"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal"
>
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="password:"
/>
<EditText
android:id="@+id/password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
4.登录界面代码
public class LoginActivity extends BasicActivity {
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if ("admin".equals(account)&& "123456".equals(password)){
//跳转到主界面
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(LoginActivity.this,"invalid",Toast.LENGTH_SHORT).show();
}
}
});
}
}
5.MainActivity中强制下线代码
Button button = (Button) findViewById(R.id.forceOffline);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送下线广播
Intent intent = new Intent("com.example.myapplication.FORCE_OFFLINE");
sendBroadcast(intent);
}
});