Implementation code of Android local broadcast and forced offline function

  • 2021-12-04 19:56:28
  • OfStack

1. Use local broadcasting

1. An example of local broadcasting


package com.example.broadcasttest2;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 private IntentFilter intentFilter;
 
 private LocalReceiver localReceiver;
 
 private LocalBroadcastManager localBroadcastManager;
 
 private NetworkChangeReceiver networkChangeReceiver;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 intentFilter = new IntentFilter();
 intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
 networkChangeReceiver = new NetworkChangeReceiver();
 registerReceiver(networkChangeReceiver,intentFilter);
 localBroadcastManager = LocalBroadcastManager.getInstance(this);// Get an instance 
 
 Button button = (Button) findViewById(R.id.button);
 button.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
 // The following line of code is used for global broadcasting 
// Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
 // The following line of code is used for local broadcasting (that is, app Internal delivery broadcast) 
 Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
 localBroadcastManager.sendBroadcast(intent);// Send a local broadcast  
// sendBroadcast(intent);
 // Let's close the top 1 Line of code, and then write another 1 Methods sendOrderedBroadcast, Send an ordered broadcast 
 sendOrderedBroadcast(intent,null);
 }
 });
 intentFilter = new IntentFilter();
 intentFilter.addAction("com.example.broadcasttest.LOCAL_BROACAST");
 localReceiver = new LocalReceiver();
 localBroadcastManager.registerReceiver(localReceiver,intentFilter);// Register a local broadcast listener 
 
 
 }
 
 @Override
 protected void onDestroy() {
 super.onDestroy();
// unregisterReceiver(networkChangeReceiver);
 localBroadcastManager.unregisterRecerver(localReceiver);
 
 }
 
 class NetworkChangeReceiver extends BroadcastReceiver{
 @Override
 public void onReceive(Context context,Intent intent) {
 ConnectivityManager connectionMananger = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo networkInfo = connectionMananger.getActiveNetworkInfo();
 if(networkInfo != null && networkInfo.isAvailable()) {
 Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show(); 
 } else {
 Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
 }
 
 }
 }
 
 class LocalReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context,Intent intent) {
 Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show();
 }
 }
}

Pass LocalBroadcastManager Adj. getInstance() Method is used to get 1 instance, and the registration broadcast is used registerReceiver() Method, the parameter passed in is localReceiver The internal instance of, 1 is the internal instance of IntentFilter Instance. Finally in onCreate The method that sends the broadcast is called in the. Finally, we send 1 in the click event of the button com.example.broadcasttest.LOCAL_BROADCAST Broadcast, and then in LocalReceiver Go inside and receive this broadcast.

Note: Local broadcasting cannot be received by static registration, which is completely understandable, because static registration is mainly to enable the program to receive broadcasting when it is not started, and when sending local broadcasting, our program has already started, because there is no need to use static registration function at all.

2. Advantages of using local broadcasting

(1) Internal transmission of programs to prevent confidential data from being leaked;
(2) Other programs can't send broadcasts to our programs to prevent hidden dangers of security vulnerabilities;
(3) It is more efficient to send local broadcasts.

2. Implement the forced offline function

1. Implement the logic of forcing offline

No matter which active interface we are in the program, once we receive the broadcast of forced offline, we will jump out of an interface. We must click "Confirm" and then jump directly to the login interface.

2. First create a class to manage all activities


package com.example.broadcastbestpractice;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;

public class ActivityCollector {
 
 public 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();
 }
 }
 }
}

3. Create a base class BaseActivity as the parent of all activities


package com.example.broadcastbestpractice;

import android.app.Activity;
import android.os.Bundle;

public class BastActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 ActivityCollector.addActivity(this);
 }
 
 @Override
 public void onDestroy() {
 super.onDestroy();
 ActivityCollector.removeActivity(this);
 }
}

4. Next, you need to establish the layout of a login page


<?xml version="1.0" encoding="utf-8"?>
<!-- 
 android:shrinkColumns Set the column sequence number allowed to be shrunk 
 android:strectColumns Set the column sequence number allowed to be stretched  -->
<TableLLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:strectColumns = "1" >
 
 <TableRow>
  <TextView
   android:layout_height = "wrap_content"
   android:text="Account:" />
  
  <EditText
   android:id="@+id/account"
   android:layout_height="wrap_content"
   android:hint="Input your account" />  
 </TableRow>
 
 <TableRow>
  <TextView
   android:layout_height="wrap_content"
   android:text="Password:" />
  
  <EditTest
   android:id="@+id/password"
   android:layout_height="wrap_content"
   android:inputType="textPassword" />  
 </TableRow>
 
 <TableRow>
  <Button
   android:id="@+id/login"
   android:layout_height="wrap_content"
   android:layout_span="2"
   android:text="Login" />
 </TableRow>

</TableLayout>

We'll continue to write the following in the next serialization.

3. Source:

BroadcastTest2
BroadcastBestPractice
https://github.com/ruigege66/Android/tree/master/BroadcastTest2
https://github.com/ruigege66/Android/tree/master/BroadcastBestPractice


Related articles: