最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

第六章 組件通訊與廣播消息(系統(tǒng)廣播 )

2018-11-08 23:48 作者:swiss126  | 我要投稿

參考資料:

《Android應(yīng)用程序開發(fā)》ISBN 9787302283164

參考軟件:

Android Studio、Eclipse+ADT、Android SDK、JDK

系統(tǒng)廣播

參考:http://www.cnblogs.com/jxldjsn/p/6135523.html

Android系統(tǒng)中內(nèi)置了多個系統(tǒng)廣播,只要涉及到手機(jī)的基本操作,基本上都會發(fā)出相應(yīng)的系統(tǒng)廣播。如:開啟啟動,網(wǎng)絡(luò)狀態(tài)改變,拍照,屏幕關(guān)閉與開啟,點(diǎn)亮不足等等。每個系統(tǒng)廣播都具有特定的intent-filter,其中主要包括具體的action,系統(tǒng)廣播發(fā)出后,將被相應(yīng)的BroadcastReceiver接收。系統(tǒng)廣播在系統(tǒng)內(nèi)部當(dāng)特定事件發(fā)生時,有系統(tǒng)自動發(fā)出。

android.permission.ACCESS_CHECKIN_PROPERTIES
允 許讀寫訪問”properties”表在checkin數(shù)據(jù)庫中,改值可以修改上傳( Allows read/write access to the “properties” table in the checkin database, to change values that get uploaded)

android.permission.ACCESS_COARSE_LOCATION
允許一個程序訪問CellID或WiFi熱點(diǎn)來獲取粗略的位置(Allows an application to access coarse (e.g., Cell-ID, WiFi) location)

android.permission.ACCESS_FINE_LOCATION
允許一個程序訪問精良位置(如GPS) (Allows an application to access fine (e.g., GPS) location)

android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
允許應(yīng)用程序訪問額外的位置提供命令(Allows an application to access extra location provider commands)

android.permission.ACCESS_MOCK_LOCATION
允許程序創(chuàng)建模擬位置提供用于測試(Allows an application to create mock location providers for testing)

android.permission.ACCESS_NETWORK_STATE
允許程序訪問有關(guān)GSM網(wǎng)絡(luò)信息(Allows applications to access information about networks)

android.permission.ACCESS_SURFACE_FLINGER
允許程序使用SurfaceFlinger底層特性(Allows an application to use SurfaceFlinger’s low level features)

android.permission.ACCESS_WIFI_STATE
允許程序訪問Wi-Fi網(wǎng)絡(luò)狀態(tài)信息(Allows applications to access information about Wi-Fi networks)

android.permission.ADD_SYSTEM_SERVICE
允許程序發(fā)布系統(tǒng)級服務(wù)(Allows an application to publish system-level services).

android.permission.BATTERY_STATS
允許程序更新手機(jī)電池統(tǒng)計信息(Allows an application to update the collected battery statistics)

android.permission.BLUETOOTH
允許程序連接到已配對的藍(lán)牙設(shè)備(Allows applications to connect to paired bluetooth devices)

android.permission.BLUETOOTH_ADMIN
允許程序發(fā)現(xiàn)和配對藍(lán)牙設(shè)備(Allows applications to discover and pair bluetooth devices)

android.permission.BRICK
請求能夠禁用設(shè)備(非常危險)(Required to be able to disable the device (very *erous!).)

android.permission.BROADCAST_PACKAGE_REMOVED
允許程序廣播一個提示消息在一個應(yīng)用程序包已經(jīng)移除后(Allows an application to broadcast a notification that an application

package has been removed)

android.permission.BROADCAST_STICKY
允許一個程序廣播常用intents(Allows an application to broadcast sticky intents)

android.permission.CALL_PHONE
允 許一個程序初始化一個電話撥號不需通過撥號用戶界面需要用戶確認(rèn)(Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.)

android.permission.CALL_PRIVILEGED
允 許一個程序撥打任何號碼,包含緊急號碼無需通過撥號用戶界面需要用戶確認(rèn)(Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed)

android.permission.CAMERA
請求訪問使用照相設(shè)備(Required to be able to access the camera device. )

android.permission.CHANGE_COMPONENT_ENABLED_STATE
允 許一個程序是否改變一個組件或其他的啟用或禁用(Allows an application to change whether an application component (other than its own) is enabled or not. )

android.permission.CHANGE_CONFIGURATION
允許一個程序修改當(dāng)前設(shè)置,如本地化(Allows an application to modify the current configuration, such as locale. )

android.permission.CHANGE_NETWORK_STATE
允許程序改變網(wǎng)絡(luò)連接狀態(tài)(Allows applications to change network connectivity state)

android.permission.CHANGE_WIFI_STATE
允許程序改變Wi-Fi連接狀態(tài)(Allows applications to change Wi-Fi connectivity state)

android.permission.CLEAR_APP_CACHE
允許一個程序清楚緩存從所有安裝的程序在設(shè)備中(Allows an application to clear the caches of all installed applications on the device. )

android.permission.CLEAR_APP_USER_DATA
允許一個程序清除用戶設(shè)置(Allows an application to clear user data)

android.permission.CONTROL_LOCATION_UPDATES
允許啟用禁止位置更新提示從無線模塊(Allows enabling/disabling location update notifications from the radio. )

android.permission.DELETE_CACHE_FILES
允許程序刪除緩存文件(Allows an application to delete cache files)

android.permission.DELETE_PACKAGES
允許一個程序刪除包(Allows an application to delete packages)

android.permission.DEVICE_POWER
允許訪問底層電源管理(Allows low-level access to power management)

android.permission.DIAGNOSTIC
允許程序RW診斷資源(Allows applications to RW to diagnostic resources. )

android.permission.DISABLE_KEYGUARD
允許程序禁用鍵盤鎖(Allows applications to disable the keyguard )

android.permission.DUMP
允許程序返回狀態(tài)抓取信息從系統(tǒng)服務(wù)(Allows an application to retrieve state dump information from system services.)

android.permission.EXPAND_STATUS_BAR
允許一個程序擴(kuò)展收縮在狀態(tài)欄,android開發(fā)網(wǎng)提示應(yīng)該是一個類似Windows Mobile中的托盤程序(Allows an application to expand or collapse the status bar. )

android.permission.FACTORY_TEST
作為一個工廠測試程序,運(yùn)行在root用戶(Run as a manufacturer test application, running as the root user. )

android.permission.FLASHLIGHT
訪問閃光燈,android開發(fā)網(wǎng)提示HTC Dream不包含閃光燈(Allows access to the flashlight )

android.permission.FORCE_BACK
允許程序強(qiáng)行一個后退操作是否在頂層activities(Allows an application to force a BACK operation on whatever is the top activity. )

android.permission.FOTA_UPDATE
暫時不了解這是做什么使用的,android開發(fā)網(wǎng)分析可能是一個預(yù)留權(quán)限.

android.permission.GET_ACCOUNTS
訪問一個帳戶列表在Accounts Service中(Allows access to the list of accounts in the Accounts Service)

android.permission.GET_PACKAGE_SIZE
允許一個程序獲取任何package占用空間容量(Allows an application to find out the space used by any package. )

android.permission.GET_TASKS
允 許一個程序獲取信息有關(guān)當(dāng)前或最近運(yùn)行的任務(wù),一個縮略的任務(wù)狀態(tài),是否活動等等(Allows an application to get information about the currently or recently running tasks: a thumbnail representation of the tasks, what activities are running in it, etc.)

android.permission.HARDWARE_TEST
允許訪問硬件(Allows access to hardware peripherals. )

android.permission.INJECT_EVENTS
允 許一個程序截獲用戶事件如按鍵、觸摸、軌跡球等等到一個時間流,android 開發(fā)網(wǎng)提醒算是hook技術(shù)吧(Allows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window.)

android.permission.INSTALL_PACKAGES
允許一個程序安裝packages(Allows an application to install packages. )

android.permission.INTERNAL_SYSTEM_WINDOW
允許打開窗口使用系統(tǒng)用戶界面(Allows an application to open windows that are for use by parts of the system user interface. )

android.permission.INTERNET
允許程序打開網(wǎng)絡(luò)套接字(Allows applications to open network sockets)

android.permission.MANAGE_APP_TOKENS
允 許程序管理(創(chuàng)建、催后、 z- order默認(rèn)向z軸推移)程序引用在窗口管理器中(Allows an application to manage (create, destroy, Z-order) application tokens in the window manager. )

android.permission.MASTER_CLEAR

目前還沒有明確的解釋,android開發(fā)網(wǎng)分析可能是清除一切數(shù)據(jù),類似硬格機(jī)

android.permission.MODIFY_AUDIO_SETTINGS
允許程序修改全局音頻設(shè)置(Allows an application to modify global audio settings)

android.permission.MODIFY_PHONE_STATE
允許修改話機(jī)狀態(tài),如電源,人機(jī)接口等(Allows modification of the telephony state – power on, mmi, etc. )

android.permission.MOUNT_UNMOUNT_FILESYSTEMS
允許掛載和反掛載文件系統(tǒng)可移動存儲(Allows mounting and unmounting file systems for removable storage. )

android.permission.PERSISTENT_ACTIVITY
允許一個程序設(shè)置他的activities顯示(Allow an application to make its activities persistent. )

android.permission.PROCESS_OUTGOING_CALLS
允許程序監(jiān)視、修改有關(guān)播出電話(Allows an application to monitor, modify, or abort outgoing calls)

android.permission.READ_CALENDAR
允許程序讀取用戶日歷數(shù)據(jù)(Allows an application to read the user’s calendar data.)

android.permission.READ_CONTACTS
允許程序讀取用戶聯(lián)系人數(shù)據(jù)(Allows an application to read the user’s contacts data.)

android.permission.READ_FRAME_BUFFER
允許程序屏幕波或和更多常規(guī)的訪問幀緩沖數(shù)據(jù)(Allows an application to take screen shots and more generally get access to the frame buffer data)

android.permission.READ_INPUT_STATE
允許程序返回當(dāng)前按鍵狀態(tài)(Allows an application to retrieve the current state of keys and switches. )

android.permission.READ_LOGS
允許程序讀取底層系統(tǒng)日志文件(Allows an application to read the low-level system log files. )

android.permission.READ_OWNER_DATA
允許程序讀取所有者數(shù)據(jù)(Allows an application to read the owner’s data)

android.permission.READ_SMS
允許程序讀取短信息(Allows an application to read SMS messages.)

android.permission.READ_SYNC_SETTINGS
允許程序讀取同步設(shè)置(Allows applications to read the sync settings)

android.permission.READ_SYNC_STATS
允許程序讀取同步狀態(tài)(Allows applications to read the sync stats)

android.permission.REBOOT
請求能夠重新啟動設(shè)備(Required to be able to reboot the device. )

android.permission.RECEIVE_BOOT_COMPLETED
允 許一個程序接收到 ACTION_BOOT_COMPLETED廣播在系統(tǒng)完成啟動(Allows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting. )

android.permission.RECEIVE_MMS
允許一個程序監(jiān)控將收到MMS彩信,記錄或處理(Allows an application to monitor incoming MMS messages, to record or perform processing on them. )

android.permission.RECEIVE_SMS
允許程序監(jiān)控一個將收到短信息,記錄或處理(Allows an application to monitor incoming SMS messages, to record or perform processing on them.)

android.permission.RECEIVE_WAP_PUSH
允許程序監(jiān)控將收到WAP PUSH信息(Allows an application to monitor incoming WAP push messages. )

android.permission.RECORD_AUDIO
允許程序錄制音頻(Allows an application to record audio)

android.permission.REORDER_TASKS
允許程序改變Z軸排列任務(wù)(Allows an application to change the Z-order of tasks)

android.permission.RESTART_PACKAGES
允許程序重新啟動其他程序(Allows an application to restart other applications)

android.permission.SEND_SMS
允許程序發(fā)送SMS短信(Allows an application to send SMS messages)

android.permission.SET_ACTIVITY_WATCHER
允許程序監(jiān)控或控制activities已經(jīng)啟動全局系統(tǒng)中(Allows an application to watch and control how activities are started globally in the system.)

android.permission.SET_ALWAYS_FINISH
允許程序控制是否活動間接完成在處于后臺時(Allows an application to control whether activities are immediately finished when put in the background.)

android.permission.SET_ANIMATION_SCALE
修改全局信息比例(Modify the global animation scaling factor.)

android.permission.SET_DEBUG_APP
配置一個程序用于調(diào)試(Configure an application for debugging.)

android.permission.SET_ORIENTATION
允許底層訪問設(shè)置屏幕方向和實(shí)際旋轉(zhuǎn)(Allows low-level access to setting the orientation (actually rotation) of the screen.)

android.permission.SET_PREFERRED_APPLICATIONS
允 許一個程序修改列表參數(shù)PackageManager.addPackageToPreferred()和 PackageManager.removePackageFromPreferred()方法(Allows an application to modify the list of preferred applications with the PackageManager.addPackageToPreferred() and PackageManager.removePackageFromPreferred() methods.)

android.permission.SET_PROCESS_FOREGROUND
允許程序當(dāng)前運(yùn)行程序強(qiáng)行到前臺(Allows an application to force any currently running process to be in the foreground.)

android.permission.SET_PROCESS_LIMIT
允許設(shè)置最大的運(yùn)行進(jìn)程數(shù)量(Allows an application to set the maximum number of (not needed) application processes that can be running. )

android.permission.SET_TIME_ZONE
允許程序設(shè)置時間區(qū)域(Allows applications to set the system time zone)

android.permission.SET_WALLPAPER
允許程序設(shè)置壁紙(Allows applications to set the wallpaper )

android.permission.SET_WALLPAPER_HINTS
允許程序設(shè)置壁紙hits(Allows applications to set the wallpaper hints)

android.permission.SIGNAL_PERSISTENT_PROCESSES
允許程序請求發(fā)送信號到所有顯示的進(jìn)程中(Allow an application to request that a signal be sent to all persistent processes)

android.permission.STATUS_BAR
允許程序打開、關(guān)閉或禁用狀態(tài)欄及圖標(biāo)Allows an application to open, close, or disable the status bar and its icons.

android.permission.SUBSCRIBED_FEEDS_READ
允許一個程序訪問訂閱RSS Feed內(nèi)容提供(Allows an application to allow access the subscribed feeds ContentProvider. )

android.permission.SUBSCRIBED_FEEDS_WRITE
系統(tǒng)暫時保留改設(shè)置,android開發(fā)網(wǎng)認(rèn)為未來版本會加入該功能。

android.permission.SYSTEM_ALERT_WINDOW
允 許一個程序打開窗口使用 TYPE_SYSTEM_ALERT,顯示在其他所有程序的頂層(Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications. )

android.permission.VIBRATE
允許訪問振動設(shè)備(Allows access to the vibrator)

android.permission.WAKE_LOCK
允許使用PowerManager的 WakeLocks保持進(jìn)程在休眠時從屏幕消失( Allows using PowerManager WakeLocks to keep

processor from sleeping or screen from dimming)

android.permission.WRITE_APN_SETTINGS
允許程序?qū)懭階PI設(shè)置(Allows applications to write the apn settings)

android.permission.WRITE_CALENDAR
允許一個程序?qū)懭氲蛔x取用戶日歷數(shù)據(jù)(Allows an application to write (but not read) the user’s calendar data. )

android.permission.WRITE_CONTACTS
允許程序?qū)懭氲蛔x取用戶聯(lián)系人數(shù)據(jù)(Allows an application to write (but not read) the user’s contacts data. )

android.permission.WRITE_GSERVICES
允許程序修改Google服務(wù)地圖(Allows an application to modify the Google service map. )

android.permission.WRITE_OWNER_DATA
允許一個程序?qū)懭氲蛔x取所有者數(shù)據(jù)(Allows an application to write (but not read) the owner’s data.)

android.permission.WRITE_SETTINGS
允許程序讀取或?qū)懭胂到y(tǒng)設(shè)置(Allows an application to read or write the system settings. )

android.permission.WRITE_SMS
允許程序?qū)懚绦?Allows an application to write SMS messages)

android.permission.WRITE_SYNC_SETTINGS
允許程序?qū)懭胪皆O(shè)置(Allows applications to write the sync settings)

android 6.0后運(yùn)行時權(quán)限的處理

參考:http://blog.csdn.net/lmj623565791/article/details/50709663

https://blog.coding.net/blog/understanding-marshmallow-runtime-permission

http://www.cnblogs.com/why168888/p/6580396.html

一、自己寫

6.0的運(yùn)行時權(quán)限,我們最終都是要支持的,通常我們需要使用如下的API

·????????intcheckSelfPermission(String permission)?用來檢測應(yīng)用是否已經(jīng)具有權(quán)限

·????????voidrequestPermissions(String[] permissions, int requestCode)?進(jìn)行請求單個或多個權(quán)限

·????????voidonRequestPermissionsResult(int requestCode, String[] permissions, int[]grantResults)?用戶對請求作出響應(yīng)后的回調(diào)

以一個請求Camera權(quán)限為例

???@Override

???public void onClick(View v) {

???????if (!(checkSelfPermission(Manifest.permission.CAMERA) ==PackageManager.PERMISSION_GRANTED)) {

??????????? requestCameraPermission();

???????}

???}

?

???private static final int REQUEST_PERMISSION_CAMERA_CODE = 1;

???private void requestCameraPermission() {

???????requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_PERMISSION_CAMERA_CODE);

???}

?

???@Override

???public void onRequestPermissionsResult(int requestCode, String[]permissions, int[] grantResults) {

???????super.onRequestPermissionsResult(requestCode, permissions,grantResults);

???????if (requestCode == REQUEST_PERMISSION_CAMERA_CODE) {

??????????? int grantResult = grantResults[0];

??????????? boolean granted = grantResult ==PackageManager.PERMISSION_GRANTED;

????????? ??Log.i(LOGTAG,"onRequestPermissionsResult granted=" + granted);

???????}

???}

通常情況下,我們會得到這樣的一個對話框

當(dāng)用戶選擇允許,我們就可以在onRequestPermissionsResult方法中進(jìn)行響應(yīng)的處理,比如打開攝像頭

當(dāng)用戶拒絕,你的應(yīng)用可能就開始危險了

當(dāng)我們再次嘗試申請權(quán)限時,彈出的對話框和之前有點(diǎn)不一樣了,主要表現(xiàn)為多了一個checkbox。如下圖

當(dāng)用戶勾選了”不再詢問“拒絕后,你的程序基本這個權(quán)限就Game Over了。

不過,你還有一絲希望,那就是再出現(xiàn)上述的對話框之前做一些說明信息,比如你使用這個權(quán)限的目的(一定要坦白)。

shouldShowRequestPermissionRationale這個API可以幫我們判斷接下來的對話框是否包含”不再詢問“選擇框。

?

一個標(biāo)準(zhǔn)的流程

if?(!(checkSelfPermission(Manifest.permission.READ_CONTACTS)?==?PackageManager.PERMISSION_GRANTED))?{

??if?(shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS))?{

??????Toast.makeText(this,?"Please?grant?the?permission?this?time",?Toast.LENGTH_LONG).show();

????}

????requestReadContactsPermission();

}?else?{

??Log.i(LOGTAG,?"onClick?granted");

}

如何批量申請

批量申請權(quán)限很簡單,只需要字符串?dāng)?shù)組放置多個權(quán)限即可。如請求代碼

private?static?final?int?REQUEST_CODE?=?1;

private?void?requestMultiplePermissions()?{

????String[]?permissions?=?{Manifest.permission.WRITE_EXTERNAL_STORAGE,?Manifest.permission.READ_PHONE_STATE};

????requestPermissions(permissions,?REQUEST_CODE);

}

對應(yīng)的界面效果是

注意:間隔較短的多個權(quán)限申請建議設(shè)置成單次多個權(quán)限申請形式,避免彈出多個對話框,造成不太好的視覺效果。

申請這么多權(quán)限豈不是很累

其實(shí)你不需要每個權(quán)限都去顯式申請,舉一個例子,如果你的應(yīng)用授權(quán)了讀取聯(lián)系人的權(quán)限,那么你的應(yīng)用也是被賦予了寫入聯(lián)系人的權(quán)限。因為讀取聯(lián)系人和寫入聯(lián)系人這兩個權(quán)限都屬于聯(lián)系人權(quán)限分組,所以一旦組內(nèi)某個權(quán)限被允許,該組的其他權(quán)限也是被允許的。

二、PermissionsUtil工具類

https://github.com/opengit/MonkeyAndroid/blob/master/app/src/main/java/com/sunjiajia/monkeyandroid/utils/PermissionsUtil.java

PermissionUtil?permissionUtil?=?PermissionUtil(MainActivity.);permissionUtil.requestPermissions(String[]{Manifest.permission.,?Manifest.permission.},????????PermissionListener()?{????????????onGranted()?{????????????????Toast.(MainActivity.,?,?Toast.).show();????????????}????????????onDenied(List<String>?deniedPermission)?{????????????????Toast.(MainActivity.,?+?deniedPermission.get(),?Toast.).show();????????????}????????????onShouldShowRationale(List<String>?deniedPermission)?{????????????????Toast.(MainActivity.,?+?deniedPermission.get()?+?,?Toast.).show();????????????}????????});

三、利用第三方類庫

https://github.com/yanzhenjie/AndPermission

https://github.com/hongyangAndroid/MPermissions

開機(jī)啟動服務(wù)

我們經(jīng)常會有這樣的應(yīng)用場合,比如消息推送服務(wù),需要實(shí)現(xiàn)開機(jī)啟動的功能。要實(shí)現(xiàn)這個功能,我們就可以訂閱系統(tǒng)“啟動完成”這條廣播,接收到這條廣播后我們就可以啟動自己的服務(wù)了。我們來看一下BootCompleteReceiver和MsgPushService的具體實(shí)現(xiàn):

1.??package?com.scott.receiver;??

2.????

3.??import?android.content.BroadcastReceiver;??

4.??import?android.content.Context;??

5.??import?android.content.Intent;??

6.??import?android.util.Log;??

7.????

8.??public?class?BootCompleteReceiver?extends?BroadcastReceiver?{??

9.????????

10.????private?static?final?String?TAG?=?"BootCompleteReceiver";??

11.??????

12.????@Override??

13.????public?void?onReceive(Context?context,?Intent?intent)?{??

14.????????Intent?service?=?new?Intent(context,?MsgPushService.class);??

15.????????context.startService(service);??

16.????????Log.i(TAG,?"Boot?Complete.?Starting?MsgPushService...");??

17.????}??

18.??

19.}??

1.??package?com.scott.receiver;??

2.????

3.??import?android.app.Service;??

4.??import?android.content.Intent;??

5.??import?android.os.IBinder;??

6.??import?android.util.Log;??

7.????

8.??public?class?MsgPushService?extends?Service?{??

9.????

10.????private?static?final?String?TAG?=?"MsgPushService";??

11.??????

12.????@Override??

13.????public?void?onCreate()?{??

14.????????super.onCreate();??

15.????????Log.i(TAG,?"onCreate?called.");??

16.????}??

17.??????

18.????@Override??

19.????public?int?onStartCommand(Intent?intent,?int?flags,?int?startId)?{??

20.????????Log.i(TAG,?"onStartCommand?called.");??

21.????????return?super.onStartCommand(intent,?flags,?startId);??

22.????}??

23.??

24.????@Override??

25.????public?IBinder?onBind(Intent?arg0)?{??

26.????????return?null;??

27.????}??

28.}??

然后我們需要在AndroidManifest.xml中配置相關(guān)信息:

1.??<!--?開機(jī)廣播接受者?-->??

2.??<receiver?android:name=".BootCompleteReceiver">??

3.??????<intent-filter>??

4.??????????<!--?注冊開機(jī)廣播地址-->??

5.??????????<action?android:name="android.intent.action.BOOT_COMPLETED"/>??

6.??????????<category?android:name="android.intent.category.DEFAULT"?/>??

7.??????</intent-filter>??

8.??</receiver>??

9.??<!--?消息推送服務(wù)?-->??

10.<service?android:name=".MsgPushService"/>??

我們看到BootCompleteReceiver注冊了“android.intent.action.BOOT_COMPLETED”這個開機(jī)廣播地址,從安全角度考慮,系統(tǒng)要求必須聲明接收開機(jī)啟動廣播的權(quán)限,于是我們再聲明使用下面的權(quán)限:

1.??<uses-permission?android:name="android.permission.RECEIVE_BOOT_COMPLETED"?/>??

經(jīng)過上面的幾個步驟之后,我們就完成了開機(jī)啟動的功能,將應(yīng)用運(yùn)行在模擬器上,然后重啟模擬器,控制臺打印如下:

如果我們查看已運(yùn)行的服務(wù)就會發(fā)現(xiàn),MsgPushService已經(jīng)運(yùn)行起來了。

?網(wǎng)絡(luò)狀態(tài)變化

在某些場合,比如用戶瀏覽網(wǎng)絡(luò)信息時,網(wǎng)絡(luò)突然斷開,我們要及時地提醒用戶網(wǎng)絡(luò)已斷開。要實(shí)現(xiàn)這個功能,我們可以接收網(wǎng)絡(luò)狀態(tài)改變這樣一條廣播,當(dāng)由連接狀態(tài)變?yōu)閿嚅_狀態(tài)時,系統(tǒng)就會發(fā)送一條廣播,我們接收到之后,再通過網(wǎng)絡(luò)的狀態(tài)做出相應(yīng)的操作。下面就來實(shí)現(xiàn)一下這個功能:

1.??package?com.scott.receiver;??

2.????

3.??import?android.content.BroadcastReceiver;??

4.??import?android.content.Context;??

5.??import?android.content.Intent;??

6.??import?android.net.ConnectivityManager;??

7.??import?android.net.NetworkInfo;??

8.??import?android.util.Log;??

9.??import?android.widget.Toast;??

10.??

11.public?class?NetworkStateReceiver?extends?BroadcastReceiver?{??

12.??????

13.????private?static?final?String?TAG?=?"NetworkStateReceiver";??

14.??????

15.????@Override??

16.????public?void?onReceive(Context?context,?Intent?intent)?{??

17.????????Log.i(TAG,?"network?state?changed.");??

18.????????if?(!isNetworkAvailable(context))?{??

19.????????????Toast.makeText(context,?"network?disconnected!",?0).show();??

20.????????}??

21.????}??

22.??????

23.????/**?

24.?????*?網(wǎng)絡(luò)是否可用?

25.?????*??

26.?????*?@param?context?

27.?????*?@return?

28.?????*/??

29.????public?static?boolean?isNetworkAvailable(Context?context)?{??

30.????????ConnectivityManager?mgr?=?(ConnectivityManager)?context.getSystemService(Context.CONNECTIVITY_SERVICE);??

31.????????NetworkInfo[]?info?=?mgr.getAllNetworkInfo();??

32.????????if?(info?!=?null)?{??

33.????????????for?(int?i?=?0;?i?<?info.length;?i++)?{??

34.????????????????if?(info[i].getState()?==?NetworkInfo.State.CONNECTED)?{??

35.????????????????????return?true;??

36.????????????????}??

37.????????????}??

38.????????}??

39.????????return?false;??

40.????}??

41.??

42.}??

再注冊一下這個接收者的信息:

1.??<receiver?android:name=".NetworkStateReceiver">??

2.??????<intent-filter>??

3.??????????<action?android:name="android.net.conn.CONNECTIVITY_CHANGE"/>??

4.??????????<category?android:name="android.intent.category.DEFAULT"?/>??

5.??????</intent-filter>??

6.??</receiver>??

因為在isNetworkAvailable方法中我們使用到了網(wǎng)絡(luò)狀態(tài)相關(guān)的API,所以需要聲明相關(guān)的權(quán)限才行,下面就是對應(yīng)的權(quán)限聲明:

1.??<uses-permission?android:name="android.permission.ACCESS_NETWORK_STATE"/>??

我們可以測試一下,比如關(guān)閉WiFi,看看有什么效果。

電量變化

如果我們閱讀軟件,可能是全屏閱讀,這個時候用戶就看不到剩余的電量,我們就可以為他們提供電量的信息。要想做到這一點(diǎn),我們需要接收一條電量變化的廣播,然后獲取百分比信息,這聽上去挺簡單的,我們就來實(shí)現(xiàn)以下:

1.??package?com.scott.receiver;??

2.????

3.??import?android.content.BroadcastReceiver;??

4.??import?android.content.Context;??

5.??import?android.content.Intent;??

6.??import?android.os.BatteryManager;??

7.??import?android.util.Log;??

8.????

9.??public?class?BatteryChangedReceiver?extends?BroadcastReceiver?{??

10.??

11.????private?static?final?String?TAG?=?"BatteryChangedReceiver";??

12.??????

13.????@Override??

14.????public?void?onReceive(Context?context,?Intent?intent)?{??

15.????????int?currLevel?=?intent.getIntExtra(BatteryManager.EXTRA_LEVEL,?0);??//當(dāng)前電量??

16.????????int?total?=?intent.getIntExtra(BatteryManager.EXTRA_SCALE,?1);??????//總電量??

17.????????int?percent?=?currLevel?*?100?/?total;??

18.????????Log.i(TAG,?"battery:?"?+?percent?+?"%");??

19.????}??

20.??

21.}??

然后再注冊一下廣播接地址信息就可以了:

1.??<receiver?android:name=".BatteryChangedReceiver">??

2.??????<intent-filter>??

3.??????????<action?android:name="android.intent.action.BATTERY_CHANGED"/>??

4.??????????<category?android:name="android.intent.category.DEFAULT"?/>??

5.??????</intent-filter>??

6.??</receiver>??

當(dāng)然,有些時候我們是要立即獲取電量的,而不是等電量變化的廣播,比如當(dāng)閱讀軟件打開時立即顯示出電池電量。我們可以按以下方式獲?。?/p>

1.??Intent?batteryIntent?=?getApplicationContext().registerReceiver(null,??

2.??????????new?IntentFilter(Intent.ACTION_BATTERY_CHANGED));??

3.??int?currLevel?=?batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL,?0);??

4.??int?total?=?batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE,?1);??

5.??int?percent?=?currLevel?*?100?/?total;??

6.??Log.i("battery",?"battery:?"?+?percent?+?"%"); ?

第六章 組件通訊與廣播消息(系統(tǒng)廣播 )的評論 (共 條)

分享到微博請遵守國家法律
武清区| 兴隆县| 永顺县| 星子县| 会宁县| 岳西县| 花莲县| 岐山县| 广宁县| 清丰县| 丘北县| 阳江市| 会昌县| 满洲里市| 罗城| 綦江县| 德阳市| 德庆县| 合山市| 绍兴县| 孟州市| 梨树县| 拉萨市| 太原市| 海宁市| 汤阴县| 阳原县| 攀枝花市| 新沂市| 饶阳县| 手机| 大埔县| 邹平县| 成安县| 南阳市| 尼勒克县| 定南县| 宣武区| 崇义县| 长乐市| 深泽县|