第12+13天BroadCastReceiver广播
第12天BroadCastReceiver廣播
- BroadCastReceiver
- 一.BroadCastReceiver介紹:
- 二.如何實現廣播
- 三.代碼案例:
- 四.廣播的分類:
- 1. 無序廣播:sendBroadcast()
- 2.有序廣播:sendOrderBroadcast()
- 3.粘性廣播:sendStickyBroadcast()
- 五.BroadCastReceiver和Notifcation 的結合使用
- 六 .本地廣播和全局廣播
- 1.全局廣播
- 2.本地廣播
- 3.實現:
- 七.獲取系統廣播:動態注冊
- 1.來電監聽
- 2.網絡狀態監聽
BroadCastReceiver
一.BroadCastReceiver介紹:
- BroadCastReceiver廣播接受者,安卓四大組件之一
- 廣播三要素:
(1)廣播發送者 : 發送廣播
(2)廣播接收者(調頻): 用于接收廣播
(3)要處理的事情 :處理廣播的相關信息, Intent有圖對象 - 廣播的使用場景:
(1)同一APP下多個組件之間傳遞數據(Activity/Fragment/Service之間傳遞數據)
(2)2個APP之間傳遞數據 - 技能get點:
(1)自定義廣播接受者
(2)使用廣播接受者進行電話攔截和短信攔截和系統電量的變化
二.如何實現廣播
步驟1:廣播接受者
(1)自定義類繼承BroadcastReceiver,重寫onReceive方法
(2)注冊廣播(安卓的四大組件都需要注冊)
- 靜態注冊:在清單文件中
- 動態注冊:在代碼中注冊(注冊和解除注冊)
步驟2:廣播發送方:sendBroadcast(Intent意圖對象)
靜態注冊和動態注冊的區別:假如說Activity是接受者:
動態注冊:
(1)廣播會跟Activity的生命周期的結束而結束;
(2)自由的控制注冊和取消,有很大的靈活性
靜態注冊:
(1)廣播不會跟隨Activity的生命周期的結束而結束,一直存在,即使應用程序關閉,也會被喚醒接受廣播
(2)全局的廣播
三.代碼案例:
(1)自定義廣播接受者類繼承BroadCastReceiver,重寫onReceiver方法
public class MyReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {//TODO 1:獲取actionString action = intent.getAction();if("android.bawei.action.customer".equals(action)){Bundle bundle = intent.getExtras();int msg=bundle.getInt("msg");Log.i("廣播", "接受到了一個廣播: "+msg);}} }(2)注冊廣播方式一:清單文件靜態注冊
<!--收音機--><receiver android:name=".MyReceiver"><!--調頻--><intent-filter><action android:name="android.bawei.action.customer" /></intent-filter></receiver>(3)注冊廣播方式二:動態注冊
onCreate():注冊廣播調用Context的registerReceiver()方法
onDestory():解除注冊調用Context的unregisterReceiver()方法
(4)發送方:sendBroad(Intent意圖對象)
//按鈕的點擊事件public void customer(View view) {Intent intent=new Intent();intent.setAction("android.bawei.action.customer");Bundle bundle=new Bundle();bundle.putString("msg","發送廣播");intent.putExtras(bundle);sendBroadcast(intent);}四.廣播的分類:
1. 無序廣播:sendBroadcast()
2.有序廣播:sendOrderBroadcast()
當發送的是有序廣播的時候,優先級越高的接受者越先接收到廣播,可以調用abortBroadCast()中斷廣播,不讓其他人接受廣播。
3.粘性廣播:sendStickyBroadcast()
將之前廣播發送方發送的消息存儲起來,普通廣播就不能接受之前發過的消息
五.BroadCastReceiver和Notifcation 的結合使用
為通知上的圖片設置點擊事件
1.自定義通知布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal" android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:src="@drawable/ic_launcher_background"android:id="@+id/iv"android:layout_width="60dp"android:layout_height="60dp"></ImageView><LinearLayoutandroid:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/tv_name"android:text="歌曲名稱"android:layout_width="wrap_content"android:layout_height="wrap_content"></TextView><TextViewandroid:id="@+id/tv_artist"android:text="歌手"android:layout_width="wrap_content"android:layout_height="wrap_content"></TextView><LinearLayoutandroid:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:layout_weight="1"android:id="@+id/iv_pre"android:src="@drawable/pre"android:layout_width="0dp"android:layout_height="wrap_content"></ImageView><ImageViewandroid:layout_weight="1"android:id="@+id/iv_play"android:src="@drawable/play"android:layout_width="0dp"android:layout_height="wrap_content"></ImageView><ImageViewandroid:layout_weight="1"android:id="@+id/iv_next"android:src="@drawable/next"android:layout_width="0dp"android:layout_height="wrap_content"></ImageView></LinearLayout></LinearLayout></LinearLayout>2.java核心代碼
//TODO 1:獲得通知管理者NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//TODO 2:創建builderRemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.no);//設置文字remoteViews.setTextViewText(R.id.tv_name,"青花瓷");remoteViews.setTextViewText(R.id.tv_artist,"周杰倫");//設置圖片:本地圖片SD卡權限// remoteViews.setImageViewResource(R.id.iv,R.drawable.pre);remoteViews.setImageViewBitmap(R.id.iv, BitmapFactory.decodeFile("/sdcard/分組通知.png"));//設置點擊+發送廣播{Intent intent = new Intent();intent.setAction("com.bawei.pre");//參數一 上下文 參數二 請求碼 參數三 intent對象 參數四 flag標記 updatePendingIntent pendingIntent = PendingIntent.getBroadcast(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);remoteViews.setOnClickPendingIntent(R.id.iv_pre, pendingIntent);}{Intent intent = new Intent();intent.setAction("com.bawei.play");//參數一 上下文 參數二 請求碼 參數三 intent對象 參數四 flag標記 updatePendingIntent pendingIntent = PendingIntent.getBroadcast(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);remoteViews.setOnClickPendingIntent(R.id.iv_play, pendingIntent);}{Intent intent = new Intent();intent.setAction("com.bawei.next");//參數一 上下文 參數二 請求碼 參數三 intent對象 參數四 flag標記 updatePendingIntent pendingIntent = PendingIntent.getBroadcast(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);remoteViews.setOnClickPendingIntent(R.id.iv_next, pendingIntent);}PendingIntent pendingIntent = PendingIntent.getActivity(this, 102, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);Notification.Builder builder = new Notification.Builder(this).setContentIntent(pendingIntent)//設置通知的跳轉到activty.setSmallIcon(R.mipmap.ic_launcher) //必須設置小圖片.setCustomContentView(remoteViews);//設置自定義布局//TODO 3:發送通知manager.notify(1,builder.build());六 .本地廣播和全局廣播
全局廣播可以跨app接受和發送數據,不安全
本地廣播只能本app發送和接受數據,安全
1.全局廣播
發送的廣播事件可被其他應用程序獲取,也能響應其他應用程序發送的廣播事件(可以通過 exported–是否監聽其他應用程序發送的廣播 在清單文件中控制) 全局廣播既可以動態注冊,也可以靜態注冊。
2.本地廣播
發送的廣播事件不被其他應用程序獲取,也不能響應其他應用程序發送的廣播事件。
本地廣播只能被動態注冊,不能靜態注冊。動態注冊或方法時需要用到LocalBroadcastManager。
3.實現:
依賴:implementation ‘androidx.localbroadcastmanager:localbroadcastmanager:1.0.0’
package com.example.day013;import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;public class MyReceiver extends BroadcastReceiver {private static final String TAG = "MyReceiver";@Overridepublic void onReceive(Context context, Intent intent) {Log.i(TAG, "onReceive: ");} } package com.example.day013;import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener{private Button send;private LocalBroadcastManager localBroadcastManager;private MyReceiver myReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);send = findViewById(R.id.send);send.setOnClickListener(this);//創建一個本地廣播localBroadcastManager = LocalBroadcastManager.getInstance(this);//動態注冊一個廣播myReceiver = new MyReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("com.feng");localBroadcastManager.registerReceiver(myReceiver,intentFilter);}@Overridepublic void onClick(View v) {int id = v.getId();switch (id) {case R.id.send:Intent intent = new Intent();intent.setAction("com.feng");//注意廣播的發送者localBroadcastManager.sendBroadcast(intent);break;default:break;}}@Overrideprotected void onDestroy() {super.onDestroy();//有注冊就有銷毀localBroadcastManager.unregisterReceiver(myReceiver);} }七.獲取系統廣播:動態注冊
更多的廣播:https://blog.csdn.net/cc_want/article/details/82344899
1.來電監聽
(1)添加權限:
android.permission.READ_PHONE_STATE(2)注冊廣播(這里用的是動態廣播)
musicRecevicer = new MusicRecevicer();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);//來電監聽 getActivity().registerReceiver(musicRecevicer,intentFilter);(3)創建接受廣播對象
class MusicRecevicer extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {if(TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())){//來電TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);telephonyManager.listen(new PhoneStateListener(){@Overridepublic void onCallStateChanged(int state, String phoneNumber) {super.onCallStateChanged(state, phoneNumber);switch (state){case TelephonyManager.CALL_STATE_RINGING://來電話musicBinder.pause();break;case TelephonyManager.CALL_STATE_IDLE://掛斷musicBinder.start();break;case TelephonyManager.CALL_STATE_OFFHOOK://童話musicBinder.pause();break;}}},PhoneStateListener.LISTEN_CALL_STATE);}}}(4)注銷掉廣播對象
@Overridepublic void onDestroyView() {super.onDestroyView();if(musicRecevicer != null){getActivity().unregisterReceiver(musicRecevicer);}}2.網絡狀態監聽
(1)添加權限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />(2)注冊廣播(這里用的是動態廣播)
musicRecevicer = new MusicRecevicer();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//網絡狀態監聽getActivity().registerReceiver(musicRecevicer,intentFilter);(3)創建接受廣播對象
class MusicRecevicer extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) { if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){//網絡ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){//有網musicBinder.start();}else{//無網musicBinder.pause();}}}}(4)注銷掉廣播對象
@Overridepublic void onDestroyView() {super.onDestroyView();if(musicRecevicer != null){getActivity().unregisterReceiver(musicRecevicer);}}總結
以上是生活随笔為你收集整理的第12+13天BroadCastReceiver广播的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电信、联通双线上网配置
- 下一篇: 涉及top名校对IB课程的分数要求