Detailed broadcast mechanism (learn Lin Guo teacher works)

To facilitate system-level message notification, Android introduces a mechanism similar messages in real life broadcast.

Android each application can be registered to broadcast their own interest, so that the program will only receive broadcast content of interest, these broadcasts may come from the system, from other applications.

Android is broadcast mainly divided into two types: standard broadcast radio and orderly.

Standard broadcast is a broadcast fully asynchronous execution, issued after the broadcast, all the broadcast receiver will receive this broadcast message at the same time.

Ordered broadcast is broadcast synchronous execution, issued after the broadcast, the same time there will only be a broadcast receiver can receive this broadcast message.

Receiving broadcast system ------ broadcast receiver

There are two registered broadcast, the registration code is called dynamic registration. In AndroidMainfest.xml registered were called the static registration.

How to create a broadcast receiver? We just need to create a new class, and it inherits BroadcastReceiver, then override the parent class onReceive () method. When this broadcasting, the onReceive () method will be implemented, we can add a specific logic in which this method.

Let's look at an example to understand the basic usage of broadcast receiver.



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

    }
      class NetworkChangeReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent){
            Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();

        }

    }
}

首先,我们在MainActivity中定义了一个内部类,让它继承BroadcastReceiver,并且重写了父类的onReceiver()方法。

接着,我们新建一个IntentFilter的实例,并且给它添加了一个值为android.net.conn.CONNECTIVITY_CHANGEaction.

接着我们又实例了一个NetworkChangeReceiver对象

调用registerReceiver()方法进行注册,将NetworhChangeReceiver的实例和IntentFilter的实例传进去。这样就实现了监听网络变化的功能。

注意,动态注册的广播接收器一定都要取消注册,我们在onDestroy()方法中通过调用unregisterReceiver()方法来实现。



发布了37 篇原创文章 · 获赞 10 · 访问量 1万+

Guess you like

Origin blog.csdn.net/OneLinee/article/details/77914725