Android 通过广播获取网络状态

Android 通过广播获取网络状态

1、隐式启动Activity添加过滤
2、根据接收到的网络状态提示用户

 package com.example.broadcasttest;
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.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

public class MainActivity extends Activity {
    //隐式启动Activity添加的过滤
    private IntentFilter intentFilter;
    private NetWorkChangeReceiver netWorkChangeReceiver;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter=new IntentFilter();
        //网络发生变化时系统会发出一个值为android.net.conn.CONNECTIVITY_CHANGE的action
        //也就是判断接收什么广播
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netWorkChangeReceiver=new NetWorkChangeReceiver();
        registerReceiver(netWorkChangeReceiver,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //最后结束注册
        unregisterReceiver(netWorkChangeReceiver);
    }
    //内部方法继承BroadcastReceiver,根据网络的变化提示用户
    class NetWorkChangeReceiver extends BroadcastReceiver{
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            //NetWorkInfo方法已经过时了,根据官方文档可以用NetworkCapabilities判断网络
            NetworkCapabilities networkCapabilities=connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
            if(networkCapabilities!=null){
                Toast.makeText(context,"连接到网络",Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(context,"连接网络失败",Toast.LENGTH_SHORT).show();
            }

        }
    }
}

AndroidManifest中添加权限

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

这样就可以在用户切换网络的时候进行提示,这里只是对网络的有无进行判断,更深的话可以对用户用的4g或者WIFI进行判断。

你可能感兴趣的:(Android 通过广播获取网络状态)