Broadcast: use broadcast to realize forced offline function

Force Offline

  • Turn off all active features
  • Landing interface and Realization of jump
  • Create a new broadcast receiver and use AlertDialog to get offline

Close all activities

  • Create an ActivityCollector class to manage all activities
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();
            }
        }
    }
}
//A List is used to hold an activity, and then an addActivity() method is provided to add an activity to the List,
//A removeActivity method is provided to remove activities from the List,
//Finally, a finishAll() method is provided to destroy all the activities stored in the List.
  • Create BaseActivity class as parent of all activities
public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
        //Add the activity you are currently creating to the activity manager.
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        ActivityCollector.removeActivity(this);
        //Indicates that an activity to be destroyed is removed from the activity manager.
    }
}

Login layout



Simple login function

public class LoginActivity extends BaseActivity {
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button login;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        accountEdit = (EditText)findViewById(R.id.account);
        passwordEdit = (EditText)findViewById(R.id.password);
        login = (Button)findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = accountEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                if(account.equals("admin")&&password.equals("123456")){
                    Intent intent = new  Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                }
                else{
                    Toast.makeText(LoginActivity.this,"account or password is invalid",Toast.LENGTH_LONG).show();
                }
            }
        });

    }
}

Forced offline function

Modify the code in MainActivity to send custom broadcast:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button forceOffline  = (Button)findViewById(R.id.force_offline);
        forceOffline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.sunlianglong.broadcastbestpractice.FORCE_OFFLINE");
                sendBroadcast(intent);
            }
        });
    }
}

New ForceOfflineReceiver class

public class ForceOfflineReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);//Build a dialog
        dialogBuilder.setTitle("Worning");
        dialogBuilder.setMessage("You are to be offline.Please try to login again");
        dialogBuilder.setCancelable(false);//Set the dialog box to not cancel
        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override   //Register button for dialog
            public void onClick(DialogInterface dialog, int which) {
                ActivityCollector.finishAll();
                //Destroy all activities
                Intent intent = new Intent(context, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //Explanation: http://www.cnblogs.com/lwbqyyumidi/p/3775479.html
                context.startActivity(intent);
                //Restart LoginActivity
            }
        });
        AlertDialog alertDialog = dialogBuilder.create();
        //Set the type of AlertDialog to ensure it can pop up normally in the broadcast receiver.

        alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alertDialog.show();
        //Because the display of Alert needs to depend on a certain Activity class. And that's what we're going to pop up
        // The prompt box is a system prompt box, that is, a global prompt box, so as long as the phone is turned on, no matter it
        // In which interface you are in now, just call alertDialog.show(), and a prompt box will pop up.
    }
}

For why I need the flag ﹣ activity ﹣ new ﹣ task flag, I here Get learning.
Set permissions and register in Android manifest.xml, and set LoginActivity as the main activity.

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW">

 <receiver android:name=".ForceOfflineReceiver">
            <intent-filter>
                <action android:name="com.sunlianglong.broadcastbestpractice.FORCE_OFFLINE">
                </action>
            </intent-filter>
        </receiver>

Design sketch:



Tags: Android xml

Posted on Tue, 31 Mar 2020 02:04:13 -0700 by freebsd_dude