The Broadcasting Foundation of the Four Components of Android

Broadcasting in Android is divided into standard broadcasting and ordered broadcasting.

Standard broadcast is an asynchronous broadcast, all broadcast receivers will receive the broadcast content at the same time, which is more efficient but cannot be truncated.

Ordered broadcast is a broadcast performed synchronously. Only one broadcast receiver will receive the message at the same time, and the broadcast receiver at this time has priority.

To receive system broadcasts:

Broadcast receivers are free to register for broadcasts of interest to them. The way to register broadcast is divided into registration in code (dynamic registration) and registration in AndroidManifest.xml (static registration).

Dynamic registration of broadcast receivers : Create a new class, inherit from BroadcastReceiver, and override the onReceive() method of the parent class.

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    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);
    }

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

    private 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();
            }
        }
    }
}

An instance of InterFilter is created in the onCreate method, and an action with a value of android.net.conn.CONNECTIVITY_CHANGE is added to it, because when the network state changes, the system will issue this broadcast, that is, the broadcast receiver If you want to listen to any broadcast, add the corresponding action here.

Call the registerReceiver() method to register. In the onReceive() method, an instance of ConnectivityManager is obtained through the getSystemService() method, which is a system service class dedicated to managing network connections. Then call the getActiveNetworkInfo() method to get an instance of NetworkInfo, and call the Network's isAvailable() method. Determine if there is a network.

In the new Android access network permissions are automatically added:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Static registration realizes boot-up : broadcasts can be received when the program is not started.

右击com.example.mypc.broadcasttest->New->Other->Broadcast Receiver 即可创建:

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_SHORT).show();
    }
}

在AndroidManifest.xml添加 :

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>            
Send a custom standard broadcast :
Modify AndroidManifest.xml to:
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
    <intent-filter>
        <action android:name="com.example.mypc.broadcasttest.MY_BROADCAST"></action>    </intent-filter>
</receiver>            

Add a button event in MainACtivity.java:

Intent intent = new Intent("com.example.mypc.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
In this way, you can receive custom standard broadcasts.


发送有序广播:
只需把sendBroadcast()改为sendOrderedBroadcast()即可,sendOrderedBroadcast接收两个参数第一个是Intent,第二个是与权限操作有关的字符串。现在只需输入null就好。

有序广播是可以截断,这部分内容到用到的时候再补充上来,在书中的182页。

使用本地广播:

之前发送的广播都是属于全局广播,具有一定的安全性。Andriod中引入了一套本地广播机制,这样广播就只可以在应用程序内部进行传递,并且广播也只接受本应用程序发出的广播。本地广播机制主要使用LocalBroadcastManager来对广播进行管理,并提供了发送广播和注册广播接收器的方法。

package com.example.mypc.localbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private  LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = localBroadcastManager.getInstance(this);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.mypc.localbroadcast.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.mypc.localbroadcast.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);
    }

    private class LocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"received local broadcast",Toast.LENGTH_LONG).show();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324521932&siteId=291194637