广播注册的两种方法

广播注册的两种方法

First-动态注册:在代码当中注册,只有在程序启动之后才能接收广播

例子:通过动态注册广播,编写一个能监听网络变化的程序.
1.新建一个广播接收的类,让它继承BroadcastReceiver,并且重写其中的onReceiver()方法,每当接收到广播的时候,具体的逻辑就在onReceiver()方法中实现。

 //在MainActivity新建一个“网络改变接收”的内部类,继承自BroadcastReceiver
class NetworkChangeReceiver extends BroadcastReceiver{
         @Override
 //接收到广播后,想要做出响应的动作在下面的onReceiver()中写
         public void onReceive(Context context, Intent intent) {
 //接收到广播后,就会显示出  “Network has change!”这条消息
             Toast.makeText(context, "Network has change!", Toast.LENGTH_SHORT).show();
         }
     }

2.想要接收什么样的广播,就添加什么样的action

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);

        //创建IntenFilter的实例
        intentFilter=new IntentFilter();
        networkChangeReceiver=new NetworkChangeReceiver();
       //网络发生变化,系统会发出android.net.conn.CONNECTIVITY_CHANGE这样的广播
       //在action添加广播内容,就能接收到相应的广播内容
      intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        //注册广播接收器,只要有intentfilter中的广播内容,就会触发networkChange的动作
        registerReceiver(networkChangeReceiver,intentFilter);
    }
                          (...省略部分...)
}

用intnentFilter传入广播接收器的内容,再用networkReceiver来作出相应
响应的动作。
3.动态注册最后需要注销广播,类似于Activity的onDestroy()。

@Override
    protected void onDestroy() {
        super.onDestroy();

        //取消注册广播接收器
        unregisterReceiver(networkChangeReceiver);
    }

完整的程序代码
注意:访问系统的网络状态需要声明权限,在AndroidManifest.xml中添加权限:

package com.example.jia.broadcasttest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
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);
        //创建IntenFilter的实例
        intentFilter=new IntentFilter();
        networkChangeReceiver=new NetworkChangeReceiver();
     intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        //注册广播接收器,只要有intentfilter中的广播内容,就会触发networkChange的动作
        registerReceiver(networkChangeReceiver,intentFilter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册广播接收器
        unregisterReceiver(networkChangeReceiver);
    }

   class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
       // ConnectivityManager是一个系统服务类,专门用于管理网络连接
            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();
            }
        }
}

Second-静态注册:在AndroidManifest.xml中注册,程序未启动也能接收到广播,然后做出相应的逻辑 。

例子:通过静态注册广播,编写一个开机自启动的程序.
1.新建一个广播接收器的类,利用AndroidStudio快速静态注册广播

广播注册的两种方法_第1张图片
静态注册广播接收器过程.png
新建好的类如下:在onReceive()函数当中即可添加自己的逻辑

public class BootCompeleteReceiver extends BroadcastReceiver {
    public BootCompeleteReceiver() {
    }

    @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 has complete!!",Toast.LENGTH_LONG).show();
    }
}

2.因为是监听系统的广播,所以需要在AndroidManifest.xml中声明权限;

3.在AndroidManifest.xml中添加广播接收器需要接受的信息;即开关机时,系统会发出一条"android.intent.action.BOOT_COMPLETED" 的广播,当广播接收器接收到这条内容时,就会执行1.中的onReceive()逻辑动作;

 
            
                
            
        

此致
敬礼

你可能感兴趣的:(广播注册的两种方法)