BroadcastReceiver
Android中的每個應用程序都可以對自己感興趣的廣播進行註冊,這樣程序就只會接收到自己關心的廣播內容,可能來自於系統,可能來自於其他應用程序。
Android中廣播主要可以分爲兩種類型,標準廣播和有序廣播。
標準廣播,異步執行,廣播發出後,所有的BroadcastReceiver幾乎同時接收到廣播消息,效率高,無法被截斷。
有序廣播則是一種同步執行,廣播接收器按照優先級順序接受廣播消息,並且前面的廣播接收器還可以截斷正在傳遞的廣播,這樣後面的廣播就無法接收到廣播消息了。
發送自定義廣播
創建廣播接收器
發送自定義廣播需要創建一個廣播接收器,即新建一個類讓他繼承BroadcastReceiver,並重寫父類中的onReceive()方法。當有廣播到來時,onReceive()方法就會得到執行。
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("", "訪問到了麼= =");
Toast.makeText(context,"收收收收收到廣播",Toast.LENGTH_SHORT).show();
}
}
註冊廣播
靜態註冊
動態註冊
在活動中添加代碼如下
MyReciver mReciver=new MyReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("com.laowang.broad");
registerReceiver(mReciver,filter);
動態註冊系統廣播需要再複寫一個方法,解綁廣播接收器,防止關閉時產生error
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReciver);
}
發送廣播
在活動中按鍵的點擊事件中添加發送廣播。
Intent intent=new Intent();
intent.setAction("com.laowang.broad");
sendBroadcast(intent);
鬧鐘DEMO
在上面的基礎上添加了倆個按鈕,分別實現打開鬧鐘和關閉鬧鐘。實現的效果是,點擊打開鬧鐘後,過五秒開始廣播,每隔三秒廣播一次。點擊關閉鬧鐘來關閉廣播。
打開鬧鐘
Intent intent2=new Intent();
intent2.setAction("com.laowang.broad");
PendingIntent pendingIntent1=PendingIntent.getBroadcast(getApplication(),0x23,intent2,PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,3000,pendingIntent1);
關閉鬧鐘
Intent intent3=new Intent();
intent3.setAction("com.laowang.broad");
PendingIntent pendingIntent2=PendingIntent.getBroadcast(getApplication(),0x23,intent3,PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.cancel(pendingIntent2);
網絡連接和刪除軟件廣播DEMO
在動態註冊廣播的基礎上面,在mainfest中添加權限以及action。實現的功能分別爲,打開wlan連接時進行廣播,以及刪除軟件時進行廣播。
//權限
<uses-permission android:name="ANDROID.PERMISSION.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.broadcast_package_removed"/>
//action
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<action android:name="ANDROID.INTENT.ACTION.PACKAGE_REMOVED"/>
整個mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.laowang.android0907" >
<uses-permission android:name="ANDROID.PERMISSION.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.broadcast_package_removed"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<action android:name="ANDROID.INTENT.ACTION.PACKAGE_REMOVED"/>
</intent-filter>
</receiver>
</application>
</manifest>