1.Android中内置了多个系统广播:只要涉及到手机的基本操作(如开机、网络状态变化、拍照等等),都会发出相应的广播
2.BroadcastReceiver(广播接收器),属于 Android 四大组件之一,在 Android 开发中,BroadcastReceiver 的应用场景非常多,一般用于组件间通信
1.BroadCastReceiver广播接受者,安卓四大组件之一
2.广播三要素:
(1)广播发送者 : 发送广播
(2)广播接收者(调频): 用于接收广播
(3)要处理的事情 :处理广播的相关信息, Intent有图对象
3.广播的使用场景:
(1)同一APP下多个组件之间传递数据(Activity/Fragment/Service之间传递数据)
(2)2个APP之间传递数据
4.技能get点:
(1)自定义广播接受者
(2)使用广播接受者进行电话监听,网络状态监听,插拔耳机监听
在Android7.0之前我们只需要静态注册一下广播就可以实现实时监听网络状态的变化;
但是在Android7.0之后,如果我们需要实时监听监听网络状态变化,需要动态注册广播;
public class Main6Activity extends AppCompatActivity {
private MyMusicRecevicer myMusicRecevicer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[]{
"android.permission.WRITE_EXTERNAL_STORAGE",
"android.permission.READ_EXTERNAL_STORAGE"
},101);
}
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notification();
}
});
myMusicRecevicer = new MyMusicRecevicer();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.bawei.pre");
intentFilter.addAction("com.bawei.play");
registerReceiver(myMusicRecevicer,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myMusicRecevicer);
}
//发送通知:自定义通知
private void notification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.icon);//必须设置
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
//图片:sd卡
remoteViews.setImageViewBitmap(R.id.iv, BitmapFactory.decodeFile("/sdcard/Pictures/hahah.jpg"));
//文字
remoteViews.setTextViewText(R.id.tv,"青花瓷");
//点击监听结合广播:发送方
Intent intent = new Intent();
intent.setAction("com.bawei.pre");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,101,intent,PendingIntent.FLAG_ONE_SHOT);
remoteViews.setOnClickPendingIntent(R.id.iv_pre,pendingIntent);
Intent intent2 = new Intent();
intent2.setAction("com.bawei.play");
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this,101,intent2,PendingIntent.FLAG_ONE_SHOT);
remoteViews.setOnClickPendingIntent(R.id.iv_play,pendingIntent2);
builder.setCustomContentView(remoteViews);//设置自定义布局
notificationManager.notify(1,builder.build());
}
class MyMusicRecevicer extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if("com.bawei.pre".equals(intent.getAction())){
Toast.makeText(context, "上一首", Toast.LENGTH_SHORT).show();
}else if("com.bawei.play".equals(intent.getAction())){
Toast.makeText(context, "播放", Toast.LENGTH_SHORT).show();
}
}
}
}