Summary

This article introduces two kinds of registration broadcasting: dynamic registration (JAVA code), static (registration in the manifest file Android Manifest. xml)

Dynamic Registered Broadcasting Receiver

Achieved results: In app MainActivity, the button to send a broadcast message is clicked to give the following feedback:

  1. Write text to EditText in MainActivity
  2. Pop up Toast
  3. Print Logcat

The operation of creating the project has been skipped. Now we begin the production of each module and the code.

  1. Make the layout file acitvity_main of MainActivity, the complete code is as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="center_horizontal"
            android:text="Received Broadcasts" />
        
        <Button
            android:id="@+id/btnSendBroadcast"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_gravity="center_horizontal"
            android:text="Send Broadcast"/>
        
        <EditText
            android:id="@+id/etReceivedBroadcast"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
  2. Making MainActivity, the complete code is as follows:

    package com.ccsoft.broadcastdemo;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    
    
    public class MainActivity extends Activity implements View.OnClickListener {
        MyReceiver myReceiver;
        IntentFilter intentFilter;
        EditText etReceivedBroadcast;
        Button btnSendBroadcast;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activit_main);
    
            etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
            btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
    
            //keep reference to Activity context
            MyApplication myApplication = (MyApplication) this.getApplicationContext();
            myApplication.mainActivity = this;
    
            btnSendBroadcast.setOnClickListener(this);
    
            myReceiver = new MyReceiver();
            intentFilter = new IntentFilter("chanchawReceiver");
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            registerReceiver(myReceiver, intentFilter);
    
        }
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(myReceiver);
        }
    
    
        @Override
        public void onClick(View view) {
    
            Intent intent = new Intent("chanchawReceiver");
            sendBroadcast(intent);
    
        }
    }
  3. After the above steps are pasted into the project, there will be some classes and objects that do not exist and cause errors. Don't worry about it. After the complete code is laid out, it will run normally. The complete code for MyApplication used in Step 2 is as follows

    package com.ccsoft.broadcastdemo;
    
    import android.app.Application;
    
    public class MyApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        MainActivity mainActivity;
    }
  4. The complete code of the receiver MyReceiver is as follows:

    package com.ccsoft.broadcastdemo;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    import android.widget.Toast;
    
    public class MyReceiver extends BroadcastReceiver {
        private static final String TAG = "chanchaw";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;
            mainActivity.etReceivedBroadcast.append("broadcast: "+intent.getAction()+"\n");
            String msg = intent.getStringExtra("msg");
    
            Toast.makeText(context, "Received!", Toast.LENGTH_LONG).show();
            Log.i(TAG,"Received the broadcast message!");
        }
    }
  5. The complete code for the project manifest file AndroidManifest.xml is as follows:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.ccsoft.broadcastdemo">
    
        <application
            android:name=".MyApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
    
            <activity android:name=".MainActivity" android:label="MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <receiver android:name="com.ccsoft.broadcastdemo.MyReceiver" >
                <intent-filter>
                    <action android:name="chanchawReceiver" />
                </intent-filter>
            </receiver>
    
        </application>
    </manifest>
  6. The final project structure is as follows:

Code interpretation

After the above steps are executed, all the code will be pasted up. Next, I will introduce the necessary knowledge points. Class MyApplication is used to bind the entire application instance, so set the attribute android:name=".MyApplication" in the application tag of the manifest file AndroidManifest.xml, which declares a variable of MainActivity type and binds the variable in the onCreate event of the page:

MyApplication myApplication = (MyApplication) this.getApplicationContext();
myApplication.mainActivity = this;

With the above preparation to use it in the receiver class MyReceiver and then assign values to the controls in Main Activity, this method is to implement "control inversion" - I call it myself - in the receiver's logic you can modify the data in other activities.

Static registration

It still needs to be tuckled down, and the information is very old. It led to the static registration method being not tested at the beginning. After that, it was discovered that the method of static registration was modified after Android 8. In the above MainActivity, clicking the button sends the broadcast code to set the receiver's package name, and then the receiver can receive the broadcast, that is, the button click event. The complete code should be:

    @Override
    public void onClick(View view) {
        Intent intent = new Intent("chanchawReceiver");
        intent.setPackage("com.ccsoft.broadcastdemo");
        sendBroadcast(intent);
    }

Also remember to comment out the overloaded methods onResume and onPause in MainActivity - these two methods are only used for dynamic registration. After simple modification, the "dynamic registration mode" will be changed to "static registration mode".

Source code

Source address: https://gitee.com/chanchaw/Br...

Warehouse Address: https://gitee.com/chanchaw/Br...