一.动态注册广播
1.布局文件
<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"
android:orientation="vertical" >
<Button
android:id="@+id/register_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="动态注册广播" />
<Button
android:id="@+id/jiechu_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="解除广播" />
</LinearLayout>
1.mainactivity
public class MainActivity extends Activity implements OnClickListener {
private Button registerButton, jiechuButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerButton = (Button) findViewById(R.id.register_button1);
jiechuButton = (Button) findViewById(R.id.jiechu_button2);
}
public void onClick(View v) {
//创建过滤器对象,标明在触发拨号的时候才会触动该广播
IntentFilter filter = new IntentFilter(
"android.intent.action.PHONE_STATE");
//设置优先级
filter.setPriority(1000);
switch (v.getId()) {
case R.id.register_button1:// 动态注册广播
/**
* 参数一:要注册的广播接收者 参数二:当前广播的过滤器
* */
registerReceiver(new MyBroadcastReceiver(), filter);
break;
case R.id.jiechu_button2:// 解除广播
unregisterReceiver(new MyBroadcastReceiver());
break;
}
}
}
3.新建MyBroadcastReceiver 类继承BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.i("myTag", "来电话了");
}
}