Android中实现进入App之后检查网络状态
1,注册广播,一般使用静动态注册,即当程序退出的时候广播接受者就收不到消息使用方法context.registerReceiver()方法在MainActivity中的OnStart()方法中执行注册,代码:
IntentFilter intentFilter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); this.registerReceiver(judgeNetIsConnectedReceiver, intentFilter);
在onStop()方法中解除绑定
if(this.judgeNetIsConnectedReceiver!=null){ this.unregisterReceiver(judgeNetIsConnectedReceiver); }
2,不多说,直接看我们的代码,创建一个BroadCaseReceiver的子类
package com.example.queryencyclopediademo01.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * 声明网络是否连接成功的广播接受者 * @author dell * */ public class JudgeNetIsConnectedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //得到是否没有网络连接成功 boolean isNotConnected=intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if(!isNotConnected || judgeNetIsConnected(context)){ Toast.makeText(context, "网络连接成功!", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(context, "您的网络不给力,请检查网络!", Toast.LENGTH_LONG).show(); } } /** * 判断网络连接是否成功 * @param context 上下文对象 * @return 网络连接是否成功 */ public static boolean judgeNetIsConnected(Context context) { //得到连接管理器对象 ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo= connectivityManager.getActiveNetworkInfo(); if(networkInfo==null){ return false; } return networkInfo.isConnected(); } }