首页 > 代码库 > android之网络状态的判断

android之网络状态的判断

第一步:接收状态信息

             (1、写setActivity方法是为了获得界面的控件设定是否隐藏

                 2、此类继承BroadcastReceiver,作用是重新广播接收者)

import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.util.Log;import android.view.View;import android.widget.TextView;import android.widget.Toast;/** * Created by Administrator on 2014/9/2. */public class ConnectionChangeReceiver extends BroadcastReceiver {    public Activity activity;    @Override    public void onReceive(Context context, Intent intent) {        boolean success = false;        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(                Context.CONNECTIVITY_SERVICE);//获取状态对象        NetworkInfo.State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();        // 判断是否正在使用WIFI网络        if (NetworkInfo.State.CONNECTED == state) {            TextView view = (TextView) activity.findViewById(R.id.network);            view.setVisibility(View.GONE);            Log.e("-------wifi-----", "连接");            success = true;        }        // 获取GPRS网络连接状态        state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();        // 判断是否正在使用GPRS网络        if (NetworkInfo.State.CONNECTED == state) {            TextView view = (TextView) activity.findViewById(R.id.network);            view.setVisibility(View.GONE);            Log.e("-------GPRS-----", "连接");            success = true;        }        if (!success) {            Log.e("-------net-----", "无连接");            TextView view = (TextView) activity.findViewById(R.id.network);            view.setVisibility(View.VISIBLE);            Toast.makeText(context, "网络状态改变", Toast.LENGTH_LONG).show();        }    }    public void setActivity(Activity activity) {        this.activity = activity;    }}

第二步:创建对象,启动广播接收者:

ConnectionChangeReceiver receiver = new ConnectionChangeReceiver(this);this.registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

第三步:在manifest中加上权限:

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

        作用是为了重新类ConnectionChangeReceiver中

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE);

        能够获取对象。

第四步:布局文件 

         初始化显示无网络连接提醒时,默认为不可见状态,即Visibility为gone

第五步:方法的重用:

         在广播接收者中加上一个改变activity的方法即可,而且不要带有构造函数,否者报错,见

第一步源码。

android之网络状态的判断