Android Broadcast Broadcastreceiver

Source: Internet
Author: User

The Android system defines a variety of broadcasts, such as the status of the battery, the receipt of the phone, and the receipt of the text message, which generates a broadcast on startup. Of course, users can also customize their own broadcasts.

When it comes to broadcasting, there must be a broadcast sender, and a broadcast receiver. The sender of the system broadcast is the system, and the custom broadcast is, of course, user-defined.

We can define a broadcast receiver to receive the broadcasts we are interested in, whether it's a system broadcast or a user-defined broadcast. This broadcast receiver must inherit to Broadcastreceiver.

The usual, first, a little basic knowledge.

A Basic knowledge1: Define a broadcast receiver, inheriting broadcastreceiver. 2: OnReceive receives the action of the broadcast and makes processing in the broadcast receiver. Different broadcasts are for a different set of action. 3: Register the broadcast in the Manifest.xml file, or register the broadcast through the Registerreceiver method, of course Unregisterreceiver can delete the broadcast. The system-defined broadcast, the action of the system broadcast, is given belowView Code
intent.action_airplane_mode_changed;//broadcast when airplane mode is turned off or turned onintent.action_battery_changed;//charging status, or the battery's power is changed//battery charge status, charge level change, cannot receive this broadcast through the formation statement, only through Context.registerreceiver () registrationIntent.action_battery_low;//indicates low battery powerIntent.action_battery_okay;//indicates that the battery is fully charged, that is, it emits a broadcast when it changes from low battery level to full powerintent.action_boot_completed;//Once the system is started, this action is broadcast once (only once). Intent.action_camera_button;//Broadcast when you press the camera button (hardware key) while taking a photoIntent.action_close_system_dialogs;//When the screen times out for the lock screen, the Android system broadcasts the action message when the user presses the power button, long press or short press (whether or not to jump out of the box).intent.action_configuration_changed;//broadcast (including changes: interface language, device orientation, etc.) issued when the device's current settings are changed, please refer to Configuration.javaintent.action_date_changed;//This broadcast will be issued when the device date has changedIntent.action_device_storage_low;//broadcast when device memory is low, this broadcast can only be used by the system, other apps are not available? INTENT.ACTION_DEVICE_STORAGE_OK;//broadcast when device memory is not enough to be sufficient, this broadcast can only be used by the system, other apps are not available? Intent.action_dock_event;////where this broadcast was issued Frameworks\base\services\java\com\android\server\dockobserver.javaintent.action_external_applications_available;////after the mobile app is complete, the broadcast (mobile means: APP2SD)intent.action_external_applications_unavailable;//when the app is being moved, the broadcast (move refers to: APP2SD)intent.action_gtalk_service_connected;//Gtalk Broadcast When a connection has been establishedintent.action_gtalk_service_disconnected;//Gtalk Broadcast When a connection has been disconnectedIntent.action_headset_plug;//broadcast when the headset is plugged into the headphone portintent.action_input_method_changed;//broadcasts that are emitted when changing input methodsintent.action_locale_changed;//broadcasts emitted when the device's current locale has changedIntent.action_manage_package_storage;//Intent.action_media_bad_removal;//SD card is not removed correctly (how to remove SD card correctly: Set--SD card and device memory--Uninstall SD card), but broadcast when the SD card is removed//broadcast: The Extended media (expansion card) has been unplugged from the SD card slot, but the mount point has not been lifted (unmount)Intent.action_media_button;//broadcast when the Media button button is pressed (hardware button) if there is a "media button" buttonintent.action_media_checking;//when inserting an external storage device, such as an SD card, the system will verify the SD card, and the broadcast is issued at this time .Intent.action_media_eject;//Unplugged a broadcast from an external mass storage device (such as an SD card, or a removable hard drive), and the broadcast will be issued with or without proper uninstallation?//broadcast: The user wants to remove the extended media (unplug the expansion card). intent.action_media_mounted;//broadcasts issued when an SD card is inserted and properly installed (recognized)//broadcast: The extended media is inserted and is already mounted. Intent.action_media_nofs;//intent.action_media_removed;//The external storage device has been removed, and this broadcast will be issued, whether or not it is uninstalled properly? //Broadcast: The extension media is removed. intent.action_media_scanner_finished;//broadcast: A directory that has been scanned for mediaIntent.action_media_scanner_scan_file;//intent.action_media_scanner_started;//Broadcast: Start scanning a directory of mediaintent.action_media_shared;//Broadcast: The Mount of the extended media is lifted (unmount) because it has been shared as a USB mass storage. intent.action_media_unmountable;//intent.action_media_unmounted//broadcast: The extended media exists, but is not mounted (mount). Intent.action_new_outgoing_call;intent. action_package_added;//after the successful installation apk//Broadcast: A new application package is installed on the device. //A new app package is already installed on the device, and the data includes the package name (the latest installed package program cannot receive this broadcast)intent.action_package_changed;//an existing application package has changed, including the package nameintent.action_package_data_cleared;//To clear the broadcast of an application's data (in Settings-app management-Select an app, then point to clear data?)//The user has cleared the data for a package, including the package name (The Purge package program cannot receive this broadcast)Intent.action_package_install;//trigger a download and complete the broadcast of the installation, such as downloading the app in the electronics market? //intent.action_package_removed;//successful deletion of an APK after the broadcast//an existing application package has been removed from the device, including the package name (the package program being installed cannot receive this broadcast)intent.action_package_replaced;//a broadcast that is issued when an existing installation package is replaced (regardless of whether the app is now installed newer or older than before, this broadcast will be issued?). )intent.action_package_restarted;//The user restarts a package, all processes of the package will be killed, and all runtime status associated with it should be removed, including the package name (restart package program cannot receive this broadcast)intent.action_power_connected;//broadcast when plugged in to an external power sourceintent.action_power_disconnected;//broadcasts issued when an external power connection has been disconnectedintent.action_provider_changed;//Intent.action_reboot;//broadcast when restarting a deviceIntent.action_screen_off;//broadcast after the screen is closedintent.action_screen_on;//broadcast after the screen is openedIntent.action_shutdown;//broadcasts issued when the system is shut downintent.action_timezone_changed;//broadcasts issued when time zones changeintent.action_time_changed;//broadcasts emitted when time is setIntent.action_time_tick;//Broadcast: The current time has changed (normal time passes). //The current time changes, sent every minute, cannot be received through the component Declaration, only through the Context.registerreceiver () method to registerintent.action_uid_removed;//A user ID has been removed from the system for the broadcast sent//intent.action_ums_connected;//broadcast when the device has entered a USB mass storage state? intent.action_ums_disconnected;//broadcast when the device has moved from a USB mass storage state to a normal state? Intent.action_user_present;//intent.action_wallpaper_changed;//broadcast when the device wallpaper has changed
Two Actual combatLet's say we listen for text messages and get the message content as Hello when prompted, and we listen to our custom broadcasts and react. The code is as followsView Code
 PackageCom.dongzi;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.telephony.SmsMessage;ImportAndroid.widget.Toast;/*** Listen for SMS message broadcasts, and MSG custom broadcasts *@author   * */ Public classSmsreceiverextendsBroadcastreceiver {//system broadcast, custom broadcast    Static FinalString sms_action= "Android.provider.Telephony.SMS_RECEIVED";Static FinalString msg_action= "COM.DONGZI.CUSTOMMSG";Static FinalString hello= "HELLO";Static FinalString bundle= "BUNDLE";    String receivemsg= ""; @Override Public voidOnReceive (context context, Intent Intent) {smsmessage[] msg=NULL; Bundle bundle=NULL;//listen to the system broadcast here .         if(Intent.getaction (). Equals (Sms_action)) {Bundle=intent.getextras ();if(Bundle! =NULL{object[] objs= (object[]) bundle.get ("PUDs"); msg=NewSmsmessage[objs.length]; for(inti=0;i<objs.length;i++) msg[i]= SMSMESSAGE.CREATEFROMPDU (byte[]) objs[i]); for(intj=0;j<msg.length;j++) {String msg_str=msg[j].getmessagebody ();if(Msg_str.equals (HELLO)) {Toast.maketext (context, MSG_STR, Toast.length_long). Show ();return; }Else{Toast.maketext (context, MSG_STR, Toast.length_long). Show ();return; }                }             }                     }//Listen to our custom broadcast here.         Else if(Intent.getaction (). Equals (Msg_action)) {Bundle=intent.getbundleextra (bundle);if(Bundle! =NULL) {String hello=bundle.getstring (hello);if(hello!=NULL&&hello.equals (Hello)) {toast.maketext (context, Hello, Toast.length_long). Show ();return; }              }         }             }}
then we can either register in the code or register in the configuration fileIntentfilter filter=new Intentfilter ();
Filter.addaction (smsreceiver.msg_action);
Registerreceiver (SMSReceiver.class.newInstance (), filter);
Unregisterreceiver (receiver)
<receiver android:name= ". Smsreceiver ">
<intent-filter>
<action android:name= "Android.provider.Telephony.SMS_RECEIVED"/>
<action android:name= "COM.DONGZI.CUSTOMMSG"/>
</intent-filter>
</receiver>
they'll intercept any action-compliant broadcasts.then we'll send the broadcast in the code. View Code
// Send custom Broadcasts     privatevoid sendcustombroadcast () {         Intent intent=new Intent ( smsreceiver.msg_action);         Bundle bundle=New bundle ();         Bundle.putstring (Smsreceiver.hello, "HELLO");         Intent.putextra (Smsreceiver.bundle, BUNDLE);        Sendbroadcast (intent);    }

Android Broadcast Broadcastreceiver

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.