Broadcast基本使用

2019-08-09  本文已影响0人  者文_

1. 基本概述

Broadcast就是应用间的全局大喇叭,即通信的一个手段。Android中每个应用程序都可以对自己感兴趣的广播进行注册,这样该程序只会接收到自己关心的广播内容。

1.1 广播类型

Android中广播主要分为两种类型:标准广播和有序广播。

2. 接收广播

想要接收广播,需要使用广播接收器,注册方法分为两种:动态与静态

2.1 动态注册

注册步骤

实例:(监听网络变化)

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
        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.isConnected()) {
                Toast.makeText(context, "network is Connected", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
            }

//            Toast.makeText(context,"network changes", Toast.LENGTH_SHORT).show();
        }
    }
}

在配置文件中注册并声明权限

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

备注

2.2 静态注册

程序在未启动的情况下就能接收到广播,就需要静态注册的方式。

简单实例:

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        Toast.makeText(context, "Boot Complete", Toast.LENGTH_LONG).show();
    }
}
<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"/>
            </intent-filter>
        </receiver>

代码解释:Android系统启动完成会发出一条值为android.intent.action.BOOT_COMPELTED的广播,在<intent-filter>中添加相应的action;监听系统开机广播需要声明权限,使用<uses-permission>标签又加入一条android.permission.RECEIVE_BOOT_COMPLETED权限

备注

3. 发送自定义广播

发送广播之前,先定义一个广播接收器:

3.1 标准广播

备注

3.2. 有序广播

由于Android8.0以后限制了隐式广播,自定义一个广播接收器,动态注册。

4. 本地广播

Android引入了一套本地广播机制,使用这个机制广播只能够在应用程序的内部进行传递,并且广播接收器也只能接收来自应用程序发出的广播。

本地广播主要使用了一个LocalBroadcastManager对广播进行管理,并提供发送广播和注册广播接收器的方法。

核心方法(使用LocalBroadcastManager管理广播)

本地广播无法通过静态注册方式来接收

实例:

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter2;
    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("com.baiheng.broadcasttest.LOCALBROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
         intentFilter2 = new IntentFilter();
        intentFilter2.addAction("com.baiheng.broadcasttest.LOCALBROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter2);//注册监听广播
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
         localBroadcastManager.unregisterReceiver(localReceiver);
    }
    
     class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
        }
    }
}

备注

上一篇下一篇

猜你喜欢

热点阅读