Android Basics Beginner Tutorial--4.3.2 Broadcastreceiver discovering

Source: Internet
Author: User

Android Basics Beginner Tutorial--4.3.2 Broadcastreceiver discovering

tags (space delimited): Android Basics Beginner Tutorial

Introduction to this section:

We have a preliminary understanding of Broadcastreceiver in the last section, and we know two types of broadcasting: standard and orderly,
Dynamic or static register of broadcast receivers, listening system broadcasts, sending broadcasts on their own. Has met our basic needs ~
But the broadcast on the front is a global broadcast!

The same means that the broadcast from our app will be received by other apps,
or other apps sent by the broadcast, our app will also receive the same, so easy to cause some security problems!

and
Android gives us a mechanism for local broadcasting, and broadcasts that use this mechanism are only propagated within the app, and
The broadcast receiver can only receive broadcasts from this app!

1. Local broadcast 1) Core use method:

PS: Local broadcast cannot be accepted by static register, more efficient than system global broadcast

2) Precautions:

3) Code Demo sample (Landing kick user offline elsewhere):

Like the same. Being executed. Let's say we use another phone to login to our account again, this is the reminder account
Log in at another terminal and then turn off all of the activity we've opened and go back to the landing page.
Let's write a simple example below:

Perform:

Code implementation:

Step 1: Prepare a activitycollector to close all activity, before using the one provided by the previous activity!

Activitycollector.java

 Public classActivitycollector {Private Staticlist<activity> activities =NewArraylist<activity> (); Public Static void addactivity(Activity activity)    {Activities.add (activity); } Public Static void removeactivity(Activity activity)    {Activities.remove (activity); } Public Static void Finishall() { for(Activity activity:activities) {if(!activity.isfinishing ())            {activity.finish (); }        }    }}

Step 2: First write to the simple baseactivity, used to inherit, and then write down the landing screen.

Baseactivity.java

public  class  baseactivity   Extends  appcompatactivity  {  @Override  protected  void  oncreate  (Bundle savedinstancestate)        {super . OnCreate (savedinstancestate);    Activitycollector.addactivity (this ); }  @Override  protected  void  ondestroy  () {super .        OnDestroy ();    Activitycollector.removeactivity (this ); }}

Loginactivity.java

 Public  class loginactivity extends baseactivity implements View. Onclicklistener {    PrivateSharedpreferences pref;PrivateSharedpreferences.editor Editor;PrivateEditText Edit_user;PrivateEditText edit_pawd;PrivateButton Btn_login;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_login); Pref = Preferencemanager.getdefaultsharedpreferences ( This);    Bindviews (); }Private void bindviews() {Edit_user = (EditText) Findviewbyid (R.id.edit_user);        Edit_pawd = (EditText) Findviewbyid (R.ID.EDIT_PAWD);        Btn_login = (Button) Findviewbyid (R.id.btn_login); Btn_login.setonclicklistener ( This); }@Override    protected void OnStart() {Super. OnStart ();if(!pref.getstring ("User",""). Equals ("") {Edit_user.settext (pref.getstring ("User","")); Edit_pawd.settext (Pref.getstring ("Pawd","")); }    }@Override     Public void OnClick(View v)        {String user = Edit_user.gettext (). toString (); String pawd = Edit_pawd.gettext (). toString ();if(User.equals ("123") &&pawd.equals ("123") {editor = Pref.edit (); Editor.putstring ("User", user); Editor.putstring ("Pawd", PAWD);            Editor.commit (); Intent Intent =NewIntent (loginactivity. This, Mainactivity.class);            StartActivity (Intent); Toast.maketext (loginactivity. This,"Yo, that's right!", Toast.length_short). Show ();        Finish (); }Else{Toast.maketext (loginactivity). This,"It's so simple to output. What about the brain? ", Toast.length_short). Show (); }    }}

Step 3: Define yourself a broadcastreceiver. Complete the popup dialog in OnReceive and launch the landing page:
Mybcreceiver.java

 Public  class mybcreceiver extends broadcastreceiver {    @Override     Public void OnReceive(FinalContext context, Intent Intent) {Alertdialog.builder Dialogbuilder =NewAlertdialog.builder (context); Dialogbuilder.settitle ("Warning:"); Dialogbuilder.setmessage ("Your account is logged in elsewhere, please login again ~"); Dialogbuilder.setcancelable (false); Dialogbuilder.setpositivebutton ("OK",NewDialoginterface.onclicklistener () {@Override                     Public void OnClick(Dialoginterface Dialog,intwhich) {Activitycollector.finishall (); Intent Intent =NewIntent (context, loginactivity.class);                        Intent.addflags (Intent.flag_activity_new_task);                    Context.startactivity (Intent);        }                });        Alertdialog Alertdialog = Dialogbuilder.create ();        Alertdialog.getwindow (). SetType (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);    Alertdialog.show (); }}

Don't forget to add the System dialog box to the Androidmanifest.xml:
< uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/>

Step 4: in Mainactivity, instantiate the Localbroadcastmanager, take him over the relevant operation, in addition to destroy
Note unregisterreceiver!

Mainactivity.java

 Public  class mainactivity extends baseactivity {    PrivateMybcreceiver Localreceiver;PrivateLocalbroadcastmanager Localbroadcastmanager;PrivateIntentfilter Intentfilter;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Localbroadcastmanager = Localbroadcastmanager.getinstance ( This);//Initialize the broadcast receiver. Set FilterLocalreceiver =NewMybcreceiver (); Intentfilter =NewIntentfilter (); Intentfilter.addaction ("Com.jay.mybcreceiver.LOGIN_OTHER");        Localbroadcastmanager.registerreceiver (Localreceiver, Intentfilter);        Button Btn_send = (button) Findviewbyid (r.id.btn_send); Btn_send.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent ("Com.jay.mybcreceiver.LOGIN_OTHER");            Localbroadcastmanager.sendbroadcast (Intent);    }        }); }@Override    protected void OnDestroy() {Super. OnDestroy ();    Localbroadcastmanager.unregisterreceiver (Localreceiver); }}

OK, so simple, don't forget to register activity Oh ~

2.Android 4.3 or above version number monitoring the start-up broadcast problem resolution:

The version number is above Android 4.3. Agree that we will install the application on the SD, we all know is the system boot
After a short interval of time, the SD card is loaded, so our application may not be able to listen to this broadcast.
So we need to both monitor the boot and listen to the SD card mount broadcast!
Other than that. Some phones may not have an SD card, so these two radio listeners we can't write to the same intetn-filter.
Instead, it should be written in two, configuration codes such as the following:

<receiver android:name=". Mybroadcastreceiver ">    <intent-filter>        <action android:name="Android.intent.action.BOOT_COMPLETED"/>    </intent-filter>    <intent-filter>        <action android:name="Android. INTENT. ACTION. media_mounted "/>        <action android:name="Android. INTENT. ACTION. media_unmounted "/>        <data android:scheme="file"/>    </intent-filter></receiver>
3. Summary of frequently used system broadcasts:

Finally, we will give you some of the systems we would normally use to broadcast it:

intent.action_airplane_mode_changed;//Broadcast when airplane mode is turned off or onintent.action_battery_changed;//Charging status. Or the battery's power is changed.//battery charge status, charge level change, can not receive this broadcast through the formation statement, only through the Context.registerreceiver () RegisterIntent.action_battery_low;//indicates low battery powerIntent.action_battery_okay;//Indicates that the battery is fully charged, i.e. the broadcast will be issued when the battery level changes from low to fullintent.action_boot_completed;//After system boot is complete. This action is broadcast once (only once). Intent.action_camera_button;//Press the camera button (Hardware button) to broadcastIntent.action_close_system_dialogs;//when the screen times out for the lock screen, when the user presses the power button, long press or short press (whether or not to jump out of the box). The Android system broadcasts this action message when the lock screen is in progressintent.action_configuration_changed;////The broadcast (contains changes: interface language, device orientation) emitted when the device's current settings are changed. etc, please refer to Configuration.java)intent.action_date_changed;This broadcast will be issued when the device date has changedIntent.action_device_storage_low;//When the device is out of memory, this broadcast can only be used by the system. Not available for other apps? INTENT.ACTION_DEVICE_STORAGE_OK;//device memory from insufficient to sufficient when the broadcast, 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; ///mobile app after completion. Broadcast (mobile means: APP2SD)intent.action_external_applications_unavailable;//When the app is being moved, the broadcast (mobile means: 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;//Change the input method when the broadcast is issuedintent.action_locale_changed;radio emitted when the device's current locale has changedIntent.action_manage_package_storage;//Intent.action_media_bad_removal;//Incorrect removal of SD card (method to correctly remove SD card: 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 mount point has not been lifted (unmount)Intent.action_media_button;//Press the "Media button" button to broadcast, if there is a "media button" button (Hardware button)intent.action_media_checking;//Insert external storage device, for example SD card. The system will verify the SD card, the broadcast 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 this broadcast will be issued whether or not the uninstallation is correct?

//Broadcast: The user wants to remove the extended media (unplug the expansion card). intent.action_media_mounted;//The broadcast that was issued when the SD card was inserted and properly installed (recognized)//Broadcast: The extended media is plugged in and is already mounted. Intent.action_media_nofs;//intent.action_media_removed;//External storage device has been removed. Will this broadcast be issued whether or not it is uninstalled properly? //Broadcast: The extended media is removed. intent.action_media_scanner_finished;//Broadcast: A folder that has been scanned for mediaIntent.action_media_scanner_scan_file;//intent.action_media_scanner_started;//Broadcast: Start scanning a folder 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 is present, but it is not mounted (mount). Intent.action_new_outgoing_call;intent. action_package_added;//Successful installation apk//Broadcast: A new application package is installed on the device. //A new app package is already installed on the device, the data contains 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;//Clear the broadcast of an application's data (in Settings-app management-select an app. Then point to clear the 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;//triggers a broadcast that is issued when a download is completed and installed. For example, to download applications in the electronics market? //intent.action_package_removed;//Successful deletion of an APK after the broadcast issued//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;//Replace a broadcast that is issued when an existing installation package (whether the app is installed today than the previous one or old, will issue this broadcast?). )intent.action_package_restarted;//The user starts a package again, the entire process of the package will be killed, the execution time state of all its contacts should be removed, including the package name (once again the package program cannot receive this broadcast)intent.action_power_connected;//Broadcast when external power is plugged inintent.action_power_disconnected;//broadcast sent when external power is disconnectedintent.action_provider_changed;//Intent.action_reboot;//Broadcast when restarting the deviceIntent.action_screen_off;//screen is closed after the broadcastintent.action_screen_on;//Broadcast after the screen is openedIntent.action_shutdown;//Broadcast when shutting down the systemintent.action_timezone_changed;//The broadcast that is issued when the time zone has changedintent.action_time_changed;//Time is set when the broadcast is issuedIntent.action_time_tick;//Broadcast: The current time has changed (normal time passes).

//当前时间改变,每分钟都发送。不能通过组件声明来接收,仅仅有通过Context.registerReceiver()方法来注冊Intent.ACTION_UID_REMOVED;//一个用户ID已经从系统中移除发出的广播//Intent.ACTION_UMS_CONNECTED;//设备已进入USB大容量储存状态时发出的广播?Intent.ACTION_UMS_DISCONNECTED;//设备已从USB大容量储存状态转为正常状态时发出的广播?Intent.ACTION_USER_PRESENT;//Intent.ACTION_WALLPAPER_CHANGED;//设备墙纸已改变时发出的广播

4. Summary of this section:

Good. The study on Broadcastreceiver is here. Suppose you have any additions or suggestions. Welcome to Ask ~
Extremely grateful

Android Basics Beginner Tutorial--4.3.2 Broadcastreceiver discovering

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.