Android in use BroadcastReceiver

1, Android broadcasting is divided into static registration and dynamic registration

2, the following is an example of a simple static registration

  • Create a succession BroadcastReceiverof sub-categories
public class DeviceBootReceiver extends BroadcastReceiver {

    private static final String TAG = DeviceBootReceiver.class.getName();
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "开机了:" + intent.getAction());
    }
}

This class functionality for receiving phone is switched on the radio.

  • In AndroidManifest.xmlthe register the component
<receiver android:name=".DeviceBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

actionValue tag is used to match the type of broadcasting, broadcasting start here.
So that when the phone is switched on, you will receive messages from the system.

Similarly, we can also monitor the application is installed, uninstall application, USB plug and other broadcast systems. Just actiona slightly different value.

<receiver android:name=".OtherStateReceiver">
    <intent-filter>
        <!--电量过低-->
        <action android:name="android.intent.action.BATTERY_LOW" />
        <!--USB连接-->
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <!--USB断开-->
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        <!--软件包安装-->
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <!--软件包卸装-->
        <action android:name="android.intent.action.PACKAGE_REMOVED" />
    </intent-filter>
</receiver>

In addition to the above broadcast boot, provided that other broadcasters such registration is successfully API Level <26 (Android8.0 or less)
. Google in order to prevent the recipient program permanent memory resource consumption, prohibit some Manifest declared receiver. We want to continue to listen, you must use dynamic registration.

3, the following is an example of a dynamic registration:

public class SystemBroadcastReceiverActivity extends AppCompatActivity {

    private SystemBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_broadcast_receiver);

        IntentFilter filter = new IntentFilter();
        //USB连接
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        //USB断开
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        receiver = new SystemBroadcastReceiver();
        registerReceiver(receiver, filter);
    }

    private class SystemBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
        }
    }

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

Then AndroidManifest.xmlregister the Activitycan.

4, custom broadcast

In front of that are broadcast receiving system, we can also send customized broadcast and reception in the same application or different applications.

Here is a static registration of custom broadcast:
  • The establishment of a Activity, a Button, send broadcast click
public class CustomSenderActivity extends AppCompatActivity {

    public static final String BROADCAST_ACTION = "com.hncj.android.manifest.CustomSenderActivity";
    public static final String BROADCAST_CONTENT = "broadcast_content";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_sender);
    }

    @SuppressLint("WrongConstant")
    public void sendBroadcast(View view) {
        Intent intent = new Intent();
        intent.setAction(BROADCAST_ACTION);
        intent.putExtra(BROADCAST_CONTENT, "我发送了广播,你看收没收到?");
        
        //解决API26及以上的Android静态注册的Receiver收不到广播
        //第一种解决方案:设置标志 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
        intent.addFlags(0x01000000); //不论是一个应用自己发自己收还是一个应用发一个应用收,都可以实现效果

        //第二种解决方案:指定包名(这里是一个应用,自己发,自己收,都在一个包下)
        //intent.setPackage(getPackageName());  //如果是给另一个应用发广播 则写成intent.setPackage("另一个项目应用接收者的包名");

        //第三种解决方案: 明确指定包名,类名
        //intent.setComponent(new ComponentName(this, CustomReceiver.class)); //如果是给另一个应用发广播 则写成 intent.setComponent(new ComponentName("另一个应用接收者包名", "另一个应用接收者类名"));

        //发送广播
        sendBroadcast(intent);
    }
}
  • Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="40dp">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="sendBroadcast"
        android:background="#008080"
        android:textSize="30dp"
        android:text="发送广播"></Button>
</LinearLayout>
  • Recipient
public class CustomReceiver extends BroadcastReceiver {

    private static final String TAG = CustomReceiver.class.getName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "我收到了来自" + action + "的广播");
    }
}
  • AndroidManifest.xmlfile
<activity android:name=".manifest.CustomSenderActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<receiver android:name=".manifest.CustomReceiver">
    <intent-filter>
        <action android:name="com.hncj.android.manifest.CustomSenderActivity" />
    </intent-filter>
</receiver>

Here is a recipient of the current project, as well as a recipient in another project, the code is basically the same.
Related API:

Send orderly broadcast:

<!--广播中携带数据-->
Bundle bundle = new Bundle();
bundle.putString("username", "nacy");
sendOrderedBroadcast(intent, null, null, null, Activity.RESULT_OK, null, bundle);

Set the priority recipients: (--1000-1000) that define which recipients to receive, the higher the priority, the sooner the received broadcast

<receiver android:name=".manifest.CustomReceiver">
    <!--priority可以设置优先级-->
    <intent-filter android:priority="9">
        <action android:name="com.hncj.android.manifest.CustomSenderActivity" />
    </intent-filter>
</receiver>

Termination of broadcasting:

<!--广播不再向下传递-->
abortBroadcast();

Remove the data broadcasting:

//取出Bundle对象,类似于一个map
 Bundle bundle = getResultExtras(true);

Set recipient who received permission :()

  • First the sender AndroidManifest.xmlto declare a permissions (package name + permission name)
<permission android:name="com.hncj.android.RECEIVER_PERMISSION" />
  • Defining Permissions recipient need to have time to send:
sendOrderedBroadcast(intent, Manifest.permission.RECEIVER_PERMISSION, null, null, Activity.RESULT_OK, null, bundle);
  • Recipients in need AndroidManifest.xmlpermissions:
<uses-permission android:name="com.hncj.android.RECEIVER_PERMISSION" />

Set the sender permission :( Who can give me)

  • In the first recipient AndroidManifest.xmlto declare a privilege
<permission android:name="com.hncj.android.SENDER_PERMISSION" />
  • Description Rights sender to have the Receiver tab:
<receiver android:name=".manifest.CustomReceiver" android:permission="com.hncj.android.SENDER_PERMISSION">
    <intent-filter android:priority="9">
        <action android:name="com.hncj.android.manifest.CustomSenderActivity" />
    </intent-filter>
</receiver> 
  • The sender AndroidManifest.xmlusage rights
<uses-permission android:name="com.hncj.android.SENDER_PERMISSION" />

There dynamically register custom broadcast, example of a dynamic registration mentioned above, only in custom content in action.

Guess you like

Origin www.cnblogs.com/wotoufahaiduo/p/11639140.html