Android基础08

广播:四大组件之一,你的应用可以使用它对外部事件进行过滤只对感兴趣的外部事件(如当电话呼入时,或者数据网络可用时)进行接收并作出响应,广播接收器没有用户界面。然而,它们可以启动一个activity或serice来响应它们接收到的消息,或者用NotificationManager来通知用户。通知可以用很多种方式来吸引用户的注意力——闪动背灯、震动、播放声音等。一般来说是在状态栏上放一个持久的图标,用户可以打开它并获取消息。

  1. 想要拦截的广播
  2. 拦截到广播之后做得动作
  3. 注册广播
  4. 取消注册
package com.example.bbw.broadcastdemo;

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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private NetworkChangeReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//决定拦截哪条广播
        receiver = new NetworkChangeReceiver();
        registerReceiver(receiver,intentFilter);//注册
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);//取消注册
    }

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

取得权限:


你可能感兴趣的:(Android基础08)