Android Introduction (8) broadcast

Original link: http://www.orlion.ga/572/

1、 Broadcasting mechanism

Each application in Android can register the broadcasts it is interested in, so that the application will only receive the broadcast content it is concerned about

The multicast may come from the system or from other applications. Android provides a complete set of APIs that allow applications to send and receive broadcasts freely. The method of sending broadcast needs the help of intent. The method of receiving broadcast needs to introduce a new concept, broadcast receiver

Broadcasting can be divided into two types:

2、 Receiving system broadcast

Android has built-in many system level broadcasts. We can get the status information of various systems by listening to these broadcasts in the application. For example, after the mobile phone is turned on, it will send a broadcast, when the battery power changes, when the time or time zone changes, it will also send a broadcast, etc. If you want to receive these broadcasts, you need to use a broadcast receiver.

1. Dynamically register to monitor network changes

There are generally two ways to register Broadcasting: registration in code (dynamic registration) and registration in androidmanifest.xml (static registration)

How to create a broadcast receiver? You only need to create a class that inherits from broadcastreceiver and override the onReceive () method of the parent class, so that when a broadcast comes, the onReceive () method will be executed, and the specific logic will be executed in this code

First, write a program to monitor network changes through dynamic registration. Create a broadcastdemo project and modify the mainactivity Code:

package ga.orlion.broadcastdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

	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);
	}
	
	class NetworkChangeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			
			ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectionManager.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();
			}
		}
	}
}

As you can see, we define an internal class networkchangereceiver in mainactivity, which inherits from broadcastreceiver and rewrites the onReceive () method of the parent class. In this way, the onReceive () method will be executed whenever the network state changes. Then observe the oncreate () method. First, we create an instance of intentfilter and add a value of android.net.conn.connectivity to it_ Why add this value to the action of change? Because when the network state changes, the system sends a message with the value android.net.conn.connectivity_ Change broadcast, that is, what broadcast our broadcast receiver wants to listen to, just add the corresponding action here. Next, we create an instance of NetworkChangeReceiver, then call the registerReceiver () method to register, pass the instance of NetworkChangeReceiver and the instance of IntentFilter, so that NetworkChangeReceiver will receive all values android.net.conn.CONNECTIVITY_. The broadcast of change realizes the function of monitoring network changes. Finally, remember that dynamically registered broadcast receivers must be unregistered. Here, we call the unregisterreceiver () method in the ondestroy () method

In addition, there is a very important point to note here. In order to ensure the security of the application, the Android system has made provisions. If the program needs to access some key information of the system, it must declare the permission in the configuration file, otherwise the program will crash directly. For example, it is necessary to declare the permission to query the network status of the system here. Open the androidmanifest.xml file and add the following permissions to query the system network status:

2. Static registration enables startup

Dynamic registration is very flexible, but it can accept broadcasting only after the program is started. If you want the program to receive broadcasting without starting, you need to use static registration.

We are going to let the program receive a startup broadcast. When the broadcast is received, we can execute the corresponding logic in onreceive() method to realize the function of startup. Create a bootcompletereceiver, which inherits from broadcastreceiver. Code:

package ga.orlion.broadcastdemo;

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) {
		
		Toast.makeText(context, "Boot Complete", Toast.LENGTH_SHORT).show();
	}
}

The broadcast receiver is no longer defined by internal class, because this class needs to be registered in androidmanifest.xml later. Modify androidmanifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ga.orlion.broadcastdemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <receiver android:name=".BootCompleteReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Claim permissions are required.

3、 Send custom broadcast

1. Send standard broadcast

First, define a broadcast receiver to receive our broadcasts, and create mybroadcastreceiver, which inherits from broadcastreceiver. Code:

package ga.orlion.broadcastdemo;

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) {
		
		Toast.makeText(context , "接收到广播了" , Toast.LENGTH_SHORT).show();
	}

}

Register in androidmanifest.xml:

<receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="ga.orlion.broadcastdemo.MY_BROADCAST" />
            </intent-filter>
        </receiver>

Then modify mainactivity:

        @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {	
				Intent intent = new Intent("ga.orlion.broadcastdemo.MY_BROADCAST");
				sendBroadcast(intent);
			}
		});
	}

A broadcast is sent when the button is clicked.

2. Send ordered broadcast

Broadcast is a kind of cross process communication, so other applications should also receive the broadcast sent by our application.

Now let's try to send an ordered broadcast

Modify mainactivity:

        @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {	
				Intent intent = new Intent("ga.orlion.broadcastdemo.MY_BROADCAST");
				sendOrderedBroadcast(intent, null);
			}
		});
	}

You can see that only one line of code needs to be changed to send an ordered broadcast, that is, the sendbroadcast () method is changed to the sendorderedbroadcast () method. The sendorderedbroadcast () method receives two parameters. The first parameter is still intent and the second parameter is a permission related string. Just pass null here.

Next, set the order of broadcast receivers in the configuration file, androidmanifest.xml:

        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter android:priority="100">
                <action android:name="ga.orlion.broadcastdemo.MY_BROADCAST" />
            </intent-filter>
        </receiver>

Mybroadcastreceiver can choose whether to allow broadcasting to continue. Modify the code in mybroadcastreceiver

package ga.orlion.broadcastdemo;

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, Toast.LENGTH_SHORT).show();
		abortBroadcast();
	}
}

If the abortBroadcast () method is invoked in the onReceive () method, it means that the broadcast will be truncated and the broadcast receiver will no longer be able to receive the broadcast.

4、 Use local broadcast

All the broadcasts we sent and received earlier belong to the system global broadcast, that is, the broadcast can be received by any other application, and we can also receive broadcasts from any other application. This can easily cause security problems. In order to simply solve the security problem of broadcasting, Android has introduced a set of local broadcasting mechanism. Broadcasting using this mechanism can only be transmitted within the application, and the broadcasting receiver can only receive from the application

Broadcast from the program. The usage of local broadcast is not complicated. It mainly uses a local broadcast manager to broadcast

And provides a method for transmitting a broadcast and registering a broadcast receiver.

Modify mainactivity:

package ga.orlion.broadcastdemo;

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

public class MainActivity extends Activity {
	
	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);
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {	
				Intent intent = new Intent("ga.orlion.broadcastdemo.LOCAL_BROADCAST");
				localBroadcastManager.sendBroadcast(intent);
			}
		});
		intentFilter = new IntentFilter();
		intentFilter.addAction("ga.orlion.broadcastdemo.LOCAL_BROADCAST");
		localReceiver = new LocalReceiver();
		localBroadcastManager.registerReceiver(localReceiver, intentFilter);
	}

	@Override
	protected void onDestroy() {
		
		super.onDestroy();
		localBroadcastManager.unregisterReceiver(localReceiver);
	}
	
	class LocalReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			
			Toast.makeText(context, "接收到本地广播", Toast.LENGTH_SHORT).show();
		}
		
	}
}

First, get an instance of localbroadcastmanager through its getInstance () method. Then, when registering the broadcast receiver, call the registerreceiver () method of localbroadcastmanager. When sending the broadcast, call the sendbroadcast() method of localbroadcastmanager

method.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>