catalogue
2. Static registration broadcast
3. Send and receive custom broadcasts
4. Cross program receive broadcast
There are two kinds of broadcasting, static broadcasting and dynamic broadcasting.
1. Dynamic method:
Rewrite the broadcast receiver to accept the broadcast and operate according to the received broadcast. It can be rewritten in context or in a new file.
class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.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(); } } }
Define some parameters to be used:
private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver;
Register broadcast in onCreate:
//Create a new instance of IntentFilter and add an action //When the network changes, the system sends out Android net. conn.CONNECTIVITY_ A broadcast of change. If you need to listen to other broadcasts, add the corresponding action intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter);
At androidmanifest Declare license in XML file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Unregister in OnDestroy:
@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeReceiver); //Note: dynamically registered broadcast receivers must be unregistered. unregisterReceiver(myBroadcastReceiver); }
2. Static registration broadcast
Static registration allows programs to receive broadcasts without starting. Register statically through the method shown in the figure.
Then it will jump to the interface shown in the figure, give the broadcast receiver a name, and click finish. The name here is
BootCompleteReceiver
Modify the corresponding code to realize the corresponding functions after receiving the corresponding broadcast.
package com.example.broadcasttest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class BootCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. // throw new UnsupportedOperationException("Not yet implemented"); Toast.makeText(context,"Boot Complete",Toast.LENGTH_LONG).show(); } }
Note: the static broadcast receiver must be in Android manifest Can only be used after being registered in the XML file:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcasttest"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application 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/Theme.BroadcastTest"> <receiver android:name=".BootCompleteReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
In this way, you can receive the startup broadcast.
Note: if your application targets a platform version of API level 26 or higher, you cannot use the manifest to declare a receiver for an implicit broadcast (there is no broadcast specifically for your application), but some Not subject to this restriction Except for implicit broadcasting. In most cases, you can use Scheduling job Instead.
3. Send and receive custom broadcasts
First define a broadcast receiver to receive customized broadcasts:
package com.example.broadcasttest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. Toast.makeText(context,"Received in mybroadcastReceiver",Toast.LENGTH_LONG).show(); } }
At androidmanifest Register the custom broadcast in the XML file
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> </receiver>
Create a button to send a broadcast
<Button android:id="@+id/send_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="send Broadcast" tools:ignore="MissingConstraints" />
Add monitor to button
//button //Click the button to send the broadcast Button button = (Button) findViewById(R.id.send_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent); // Toast.makeText(MainActivity.this,"the Broadcast has been sent",Toast.LENGTH_SHORT).show(); } });
Receive broadcast in OnCreate:
//Listen to your own broadcast IntentFilter myIntentFilter = new IntentFilter(); myIntentFilter.addAction("com.example.broadcasttest.MY_BROADCAST"); myBroadcastReceiver = new MyBroadcastReceiver(); registerReceiver(myBroadcastReceiver,myIntentFilter);
4. Cross program receive broadcast
Broadcast is a kind of communication mode that can cross processes. Broadcast sent by one application can also be received by other applications.
Define a broadcast receiver in another project and register:
package com.example.broadcasttest2; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class AnotherBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. Toast.makeText(context,"Received in AnotherbroadcastReceiver",Toast.LENGTH_LONG).show(); } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcasttest2"> <application 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/Theme.BroadcastTest2"> <receiver android:name=".AnotherBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> </receiver> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
And receive the broadcast in OnCreate
package com.example.broadcasttest2; import androidx.appcompat.app.AppCompatActivity; import android.content.IntentFilter; import android.os.Bundle; public class MainActivity extends AppCompatActivity { private AnotherBroadcastReceiver anotherBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Listen to your own broadcast IntentFilter myIntentFilter = new IntentFilter(); myIntentFilter.addAction("com.example.broadcasttest.MY_BROADCAST"); anotherBroadcastReceiver = new AnotherBroadcastReceiver(); registerReceiver(anotherBroadcastReceiver,myIntentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(anotherBroadcastReceiver); } }
After that, we open the first program and click the button to send the broadcast. The prompt that the first program receives the broadcast will appear on the screen, and then the prompt that the second program receives the broadcast will pop up.