BroadcastReceiver动态注册案例演示
此案例共介绍2种动态注册广播接收器,为自定义广播接收器和系统广播接收器。当点击发送按钮后,将会弹出收到自定义广播的提示;当打开或关闭飞行模式时,会出现飞行模式发生变化的提示。
效果图:
代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyBroadcastReceiver receiver1;
private NetReceiver receiver2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver1 = new MyBroadcastReceiver();
IntentFilter filter1 = new IntentFilter();
filter1.addAction("com.example.a01dynamicregister");
registerReceiver(receiver1, filter1);
receiver2 = new NetReceiver();
IntentFilter filter2 = new IntentFilter();
filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(receiver2, filter2);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("com.example.a01dynamicregister");
sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (receiver1 != null) {
unregisterReceiver(receiver1);
}
if (receiver2 != null) {
unregisterReceiver(receiver2);
}
}
}
class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(context, "收到自定义广播了~~action为:" + action, Toast.LENGTH_LONG).show();
}
}
class NetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Toast.makeText(context, "飞行模式发生变化~~", Toast.LENGTH_LONG).show();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送自定义广播"/>
</LinearLayout>
|