Android's BroadcastReceiver Paodingjieniu

Introduction to this section:

In the previous section, we already had a preliminary understanding of BroadcastReceiver, knowing two types of broadcasts: standard and ordered, dynamic or static registration of broadcast receivers, monitoring system broadcasts, and sending broadcasts by ourselves! It has met our basic needs~ But the broadcasts written above are all global broadcasts! This also means that broadcasts sent by our APP will be received by other APPs, or broadcasts sent by other APPs will also be received by our APP, which may easily cause some security problems! And Android provides us with a local broadcast mechanism, broadcasts sent using this mechanism will only be broadcast within the APP, and broadcast receivers can only receive broadcasts sent by this application!


1. Local Broadcasting

1) Core usage:

PS: Local broadcasts cannot be accepted through static registration, which is more efficient than system global broadcasts

2) Precautions:

3) Code example (login elsewhere to kick the user offline):

Like WeChat, if we use another mobile phone to log in to our account again in the running WeChat, the previous one will remind the account to log in on another terminal, and then close all the activities we opened, and then return to the login page So ~
let's write a simple example below:

Running effect diagram:

Code:

Step 1 : Prepare an ActivityCollector that closes all activities, here is the one provided by the previous activity!

ActivityCollector.java

public class ActivityCollector {
    private static List<Activity> activities = new ArrayList<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 the simple BaseActivity for inheritance, and then write the login interface!

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{


    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    private EditText edit_user;
    private EditText edit_pawd;
    private Button 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 = new Intent(LoginActivity.this, MainActivity.class); 
            startActivity(intent); 
            Toast.makeText(LoginActivity .this,"Yo, you got it right~",Toast.LENGTH_SHORT).show(); 
            finish(); 
        }else{ 
            Toast.makeText(LoginActivity.this,"It's so simple to output, what's your brain?",Toast. LENGTH_SHORT).show(); 
        } 

    } 
}

Step 3 : Customize a BroadcastReceiver, complete the pop-up dialog box operation in onReceive, and start the landing page:  MyBcReceiver.java

public class MyBcReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(final Context context, Intent intent) { 
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); 
        dialogBuilder.setTitle("Alert:"); 
        dialogBuilder.setMessage("Your The account is logged in elsewhere, please log in again~"); 
        dialogBuilder.setCancelable(false); 
        dialogBuilder.setPositiveButton("OK", 
                new DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) {  
                        ActivityCollector.finishAll ();
                        Intent intent = new Intent(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 permission in AndroidManifest.xml:  < uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Step 4: In MainActivity, instantiate localBroadcastManager, use it to complete related operations, and pay attention to unregisterReceiver when destroying it!

MainActivity.java

public class MainActivity extends BaseActivity {

    private MyBcReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        //初始化广播接收者,设置过滤器
        localReceiver = new MyBcReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.jay.mybcreceiver.LOGIN_OTHER");
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);

        Button btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.jay.mybcreceiver.LOGIN_OTHER");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }
}

Ok, it's that simple, don't forget to register the Activity~


2. Solve the problem of listening to the start-up broadcast on Android 4.3 and above:

In Android 4.3 and above, we are allowed to install the application on the SD card. We all know that the SD card is loaded after a short period of time after the system is turned on, so our application may not be able to listen to this broadcast! So we need to monitor both the boot broadcast and the SD card mount broadcast!

In addition, some mobile phones may not have an SD card, so we cannot write these two broadcast monitors into the same Intetn-filter, but should write them into two. The configuration code is as follows:

<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. Commonly used system broadcast summary:

Finally, I would like to provide you with some system broadcasts that we may usually use:

intent.action.AIRPLANE_MODE; 
//Broadcast when airplane mode is turned off or on 

Intent.ACTION_BATTERY_CHANGED; 
//Charging status, or battery power changes 
//Battery charging status, charge level changes, you cannot receive this broadcast by building a statement, Only register 
Intent.ACTION_BATTERY_LOW through Context.registerReceiver() 
; 

// 
Indicates 
that the battery power is 

low After completion, this action is broadcast once (and only once). 
Intent.ACTION_CAMERA_BUTTON; //Broadcast 
Intent.ACTION_CLOSE_SYSTEM_DIALOGS 
sent when the camera button (hardware button) is pressed when taking pictures ; 
//When the screen times out to lock the screen, when the user presses the power button, long press or short press (regardless of The dialog box does not pop up), when the screen is locked, the android system will broadcast this Action message 
Intent.ACTION_CONFIGURATION_CHANGED; 
//The broadcast sent when the current device settings are changed (including changes: interface language, device orientation, etc., please refer to Configuration. java) 
Intent.ACTION_DATE_CHANGED; 
//This broadcast will be sent when the device date changes






Intent.ACTION_DEVICE_STORAGE_LOW; 
//Broadcast sent when the device memory is insufficient, this broadcast can only be used by the system, other APPs are not available? 

Intent.ACTION_DEVICE_STORAGE_OK; 
//The broadcast sent when the device memory is insufficient to sufficient, this broadcast can only be used by the system, and other APPs are not available? 

Intent.ACTION_DOCK_EVENT; 
// 
//The place where this broadcast is issued frameworks\base\services\java\com\android\server\DockObserver.java 

Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE; 
After the mobile APP is completed, the broadcast is sent (mobile refers to: APP2SD) 

Intent .ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 
//The broadcast sent when the APP is being moved (mobile refers to: APP2SD) 

Intent.ACTION_GTALK_SERVICE_CONNECTED; 
//The broadcast Intent sent when Gtalk has established 

a connection.ACTION_GTALK_SERVICE_DISCONNECTED; //The broadcast 
Intent 
sent when Gtalk has been disconnected 
.ACTION_HEADSET_PLUG; 
//Broadcast Intent.ACTION_INPUT_METHOD_CHANGED sent when a headset is plugged into the headset port 

; 
//The broadcast sent when the input method is changed 

Intent.ACTION_LOCALE_CHANGED;

//Broadcast Intent.ACTION_MANAGE_PACKAGE_STORAGE 
sent when the current locale of the device has been changed 
; 

//Intent.ACTION_MEDIA_BAD_REMOVAL; 
//The SD card was not removed correctly (the correct way to remove the SD card: Settings--SD card and device memory--uninstall SD card), but the broadcast sent when the SD card has been taken out 
//Broadcast: The expansion medium (expansion card) has been pulled out from the SD card slot, but the mount point (mount point) has not been released (unmount) 

Intent. ACTION_MEDIA_BUTTON; 
//The broadcast sent when the "Media Button" button is pressed, if there is a "Media Button" button (hardware button) 

Intent.ACTION_MEDIA_CHECKING; 
//When inserting an external storage device, such as an SD card, the system will check the SD card, The broadcast sent at this time? 
Intent.ACTION_MEDIA_EJECT; 
//The broadcast sent by the external large-capacity storage device (such as SD card, or mobile hard disk) has been unplugged, and this broadcast will be sent regardless of whether it is uninstalled correctly? //Broadcast: the user 
wants Remove the expansion media (unplug the expansion card). 
Intent.ACTION_MEDIA_MOUNTED; 
//The broadcast sent when the SD card is inserted and installed (recognized) correctly 
//Broadcast: the expansion medium is inserted and mounted. 
Intent.ACTION_MEDIA_NOFS; 
//
Intent.ACTION_MEDIA_REMOVED; 
//The external storage device has been removed, whether it is properly uninstalled or not, will this broadcast be sent? 
// Broadcast: Extended media removed. 
Intent.ACTION_MEDIA_SCANNER_FINISHED; 
// 
Broadcast 
: 
A 
directory 
of the media has been 
scanned (unmount) because it is already shared as USB mass storage. 
 Intent.ACTION_MEDIA_UNMOUNTABLE; 
// 
Intent.ACTION_MEDIA_UNMOUNTED 
// Broadcast: The extended media exists, but has not been mounted yet. 
Intent.ACTION_NEW_OUTGOING_CALL; 
Intent.ACTION_PACKAGE_ADDED; 
// After successful APK installation 
// Broadcast: A new application package is installed on the device. 
//A new application package has been 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 been changed, including the package name 
Intent.ACTION_PACKAGE_DATA_CLEARED;
//The broadcast sent when clearing the data of an application (in Settings - Application Management - select an application, then click Clear Data?) //The user has cleared the data 
of a package, including the package name (clear package program Cannot receive this broadcast) 

Intent.ACTION_PACKAGE_INSTALL; 
//Trigger a broadcast when a download is completed and the installation is completed, such as downloading an application in the electronic market? 
// 
Intent.ACTION_PACKAGE_REMOVED; 
//Broadcast sent after successful deletion of an APK 
//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; 
//The broadcast sent when an existing installation package is replaced (regardless of whether the installed APP is newer or older than the previous one, will this broadcast be sent?) Intent.ACTION_PACKAGE_RESTARTED; //The user restarts 
a 
package, the package's All processes will be killed, and all associated runtime state should be removed, including the package name (restart package programs cannot receive this broadcast) Intent.ACTION_POWER_CONNECTED; 
// Broadcast 
Intent.ACTION_POWER_DISCONNECTED 
sent when an external power supply is plugged in ; //Broadcast 
Intent.ACTION_PROVIDER_CHANGED 
when the external power supply is disconnected 
; 
//Broadcast when the device is restarted

Intent.ACTION_REBOOT; 

Intent.ACTION_SCREEN_OFF; //Broadcast 
Intent.ACTION_SCREEN_ON 
after the screen is turned off ; //Broadcast 
Intent.ACTION_SHUTDOWN 
after the screen is turned on ; //Broadcast 
Intent.ACTION_TIMEZONE_CHANGED 
when the system is turned off ; 
//When the time zone changes Broadcast Intent.ACTION_TIME_CHANGED issued 
; //Broadcast 
Intent.ACTION_TIME_TICK 
issued when the time is set ; 
//Broadcast: The current time has changed (normal time lapse). 
//Current time changes, sent every minute, can't be received through component declaration, only through Context.registerReceiver() method to register 
Intent.ACTION_UID_REMOVED; 
//A broadcast sent by a user ID has been removed from the system 
// 
Intent. ACTION_UMS_CONNECTED; 
//Broadcast when the device has entered the USB mass storage state? 
Intent.ACTION_UMS_DISCONNECTED; 
//Broadcast when the device has changed from the USB mass storage state to the normal state? 
Intent. ACTION_USER_PRESENT; 
//










Intent.ACTION_WALLPAPER_CHANGED; 
//Broadcast when the device wallpaper has changed

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131332384