[android]代码库
1.新建一个类extends BroadcastReceiver,并重写父类的onReceive()方法
3.在onCreat()方法中创建一个IntentFilter的实例,注册要接收的广播类型
代码:
public class BroadCastTest extends AppCompatActivity {
private IntentFilter intentFilter;
private NetWorkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad_cast_test);
intentFilter=new IntentFilter();
intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
networkChangeReceiver=new NetWorkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
}
//动态注册,最后一定要销毁
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
class NetWorkChangeReceiver extends BroadcastReceiver {
@Override
//接收到广播后,要执行的代码
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "音量改变 ", Toast.LENGTH_LONG).show();
}
}
}
中级程序员
by: 觉 发表于:2017-09-19 16:17:51 顶(0) | 踩(0) 回复
回复评论