本文實(shí)例講述了Android開發(fā)中BroadcastReceiver用法。分享給大家供大家參考。具體分析如下:
在Android系統(tǒng)中,廣播(Broadcast)是在組件之間傳播數(shù)據(jù)(Intent)的一種機(jī)制。
Braodcast Receiver顧名思義就是廣播接收器,它和事件處理機(jī)制類似,但是事件處理機(jī)制是程序組件級(jí)別的(比如:按鈕的單擊事件),而廣播事件處理機(jī)制是系統(tǒng)級(jí)別的。我們可以用Intent來啟動(dòng)一個(gè)組件,也可以用sendBroadcast()方法發(fā)起一個(gè)系統(tǒng)級(jí)別的事件廣播來傳遞消息。我們同樣可以在自己的應(yīng)用程序中實(shí)現(xiàn)Broadcast Receiver來監(jiān)聽和響應(yīng)廣播的Intent。
事件的廣播通過創(chuàng)建Intent對(duì)象并調(diào)用sendBroadcast()方法將廣播發(fā)出。事件的接受是通過定義一個(gè)繼承BroadcastReceiver的類來實(shí)現(xiàn)的,繼承該類后覆蓋其onReceive()方法,在該方法中響應(yīng)事件。
下面是android系統(tǒng)中定義了很多標(biāo)準(zhǔn)的Broadcast Action來響應(yīng)系統(tǒng)的廣播事件。
?、貯CTION_TIME_CHANGED(時(shí)間改變時(shí)觸發(fā))
?、贏CTION_BOOT_COMPLETED(系統(tǒng)啟動(dòng)完成后觸發(fā))--比如有些程序開機(jī)后啟動(dòng)就是用這種方式來實(shí)現(xiàn)的
?、跘CTION_PACKAGE_ADDED(添加包時(shí)觸發(fā))
④ACTION_BATTERY_CHANGED(電量低時(shí)觸發(fā))
下面看一個(gè)例子:
我們?cè)谝粋€(gè)按鈕上綁定一個(gè)事件,事件通過發(fā)送一個(gè)廣播來觸發(fā)logcat打出一個(gè)log。
先看manifest文件。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.broadcast.BroadcastReceiverActivity" android:label="@string/app_name_bc" > <intent-filter> <action android:name="android.intent.action.MAIN" > </action> <category android:name="android.intent.category.LAUNCHER" > </category> </intent-filter> </activity> <receiver android:name="com.example.broadcast.HelloBroadReciever" > <intent-filter> <action android:name="comz.test.printlog" > </action> </intent-filter> </receiver> </application> </manifest>新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注