Android网络连接状态2

原创文章,转载请指明出处并保留原文url地址

前面我们已经编写程序,来判断网络连接状况, 今天我们在那个程序基础上,补充网络状态检测, 可以检测到时那个类型的网络连接.

同时我们添加了, 网络状态变化监听功能,在网络状况发生变化时, 可以快速发现网络状态的变化.这样可以通知我们的程序进行相关的处理工作.

下面是几个状态检测情况的显示

wps_clip_image-31933_thumb[1]

wps_clip_image-13909_thumb[1]

在发送任何HTTP请求前最好检查下网络连接状态,这样可以避免异常。这个教程将会介绍怎样在你的应用中检测网络连接状态。

创建新的项目

1.在Eclipse IDE中创建一个新的项目并把填入必须的信息。 File->New->Android Project

创建完项目结构如下:

wps_clip_image-10391

2.创建新项目后的第一步是要在AndroidManifest.xml文件中添加必要的权限。

    为了访问网络我们需要 INTERNET 权限

为了检查网络状态我们需要 ACCESS_NETWORK_STATE 权限

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="cn.iigrowing.android.network.connection.info"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk android:minSdkVersion="9" />

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

<activity

android:label="@string/app_name"

android:name="cn.iigrowing.android.network.connection.info.InternetConnectionActivity" >

<intent-filter >

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

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

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

</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Detect Internet Status" />

<Button

android:id="@+id/btn_check"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:text="Check Internet Status" />

</RelativeLayout>

网络连接状态检测类

ConnectionDetector.java

/*

* Copyright (C) 2010 network authors

*

* @author shao

*

* @date 2013.9.21

*

* @blog http://www.iigrowing.cn/

*

* 本程序是android客户端软件演示程序

*

*/

package cn.iigrowing.android.network.connection.info;

import android.content.Context;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context) {

this._context = context;

}

public boolean isConnectingToInternet() {

ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivity != null) {

NetworkInfo[] info = connectivity.getAllNetworkInfo();

if (info != null)

for (int i = 0; i < info.length; i++)

if (info[i].getState() == NetworkInfo.State.CONNECTED) {

return true;

}

}

return false;

}

public boolean isNetworkConnected(Context context) {

if (context != null) {

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

NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if (mNetworkInfo != null) {

return mNetworkInfo.isAvailable();

}

}

return false;

}

public boolean isWifiConnected(Context context) {

if (context != null) {

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

NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWiFiNetworkInfo != null) {

return mWiFiNetworkInfo.isAvailable();

}

}

return false;

}

public boolean isMobileConnected(Context context) {

if (context != null) {

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

NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (mMobileNetworkInfo != null) {

return mMobileNetworkInfo.isAvailable();

}

}

return false;

}

public static String getConnectedTypeInfo(Context context) {

StringBuilder sb=new StringBuilder();

if (context != null) {

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

NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {

sb.append("\r\nDetailedState:" + mNetworkInfo.getDetailedState());

sb.append("\r\nExtraInfo:" + mNetworkInfo.getExtraInfo());

sb.append("\r\nReason:" + mNetworkInfo.getReason());

sb.append("\r\nState:" + mNetworkInfo.getState());

sb.append("\r\nSubtypeName:" + mNetworkInfo.getSubtypeName());

sb.append("\r\nSubtype:" + mNetworkInfo.getSubtype());

sb.append("\r\nTypeName:" + mNetworkInfo.getTypeName());

sb.append("\r\nType:" + mNetworkInfo.getType());

return sb.toString();

}

}

return "";

}

public static int getConnectedType(Context context) {

if (context != null) {

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

NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {

return mNetworkInfo.getType();

}

}

return -1;

}

}

InternetConnectionActivity.java

/*

* Copyright (C) 2010 network authors

*

* @author shao

*

* @date 2013.9.21

*

* @blog http://www.iigrowing.cn/

*

* 本程序是android客户端软件演示程序

*

*/

package cn.iigrowing.android.network.connection.info;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.IntentFilter;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

public class InternetConnectionActivity extends Activity {

// flag for Internet connection status

Boolean isInternetPresent = false;

// Connection detector class

ConnectionDetector cd;

@Override

protected void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

if (connectionReceiver != null) {

unregisterReceiver(connectionReceiver);

}

}

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button btnStatus = (Button) findViewById(R.id.btn_check);

// ConnectivityManager.

// 注册一个 广播的接受者,来接受网络广播情况

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

registerReceiver(connectionReceiver, intentFilter);

// creating connection detector class instance

cd = new ConnectionDetector(getApplicationContext());

/**

* Check Internet status button click event

* */

btnStatus.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

StringBuilder sb = new StringBuilder();

// get Internet status

isInternetPresent = cd.isConnectingToInternet();

if (isInternetPresent) {

sb.append("连接到互联网\r\n");

} else {

sb.append("未  连接到 互联网\r\n");

}

boolean wifi = cd.isWifiConnected(InternetConnectionActivity.this);

if (wifi) {

sb.append("连接采用了  wifi\r\n");

} else {

sb.append("连接  没有采用 wifi\r\n");

}

boolean mobile = cd.isMobileConnected(InternetConnectionActivity.this);

if (mobile) {

sb.append("连接采用了  3g\r\n");

} else {

sb.append("连接  没有采用 3g\r\n");

}

int i = cd.getConnectedType(InternetConnectionActivity.this);

String info = cd.getConnectedTypeInfo(InternetConnectionActivity.this);

// check for Internet status

if (isInternetPresent) {

// Internet Connection is Present

// make HTTP requests

showAlertDialog(InternetConnectionActivity.this, "Internet Connection", "You have internet connection\r\n" + sb.toString() + "\r\n" + info,

true);

} else {

// Internet connection is not present

// Ask user to connect to Internet

showAlertDialog(InternetConnectionActivity.this, "No Internet Connection", "You don’t have internet connection.\r\n" + sb.toString()

+ "\r\n" + info, false);

}

}

});

}

public void showAlertDialog(Context context, String title, String message, Boolean status) {

AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// Setting Dialog Title

alertDialog.setTitle(title);

// Setting Dialog Message

alertDialog.setMessage(message);

// Setting alert dialog icon

alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

// Setting OK Button

alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

}

});

// Showing Alert Message

alertDialog.show();

}

BroadcastReceiver connectionReceiver = new BroadcastReceiver() {

// 接受 网络状况发生变化情况

@Override

public void onReceive(Context context, Intent intent) {

ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

String s = "";

if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {

Log.i("aaa", "unconnect");

s = "未连接(unconnect)\r\n";

} else {

Log.i("aaa", "connect network");

s = "已连接(connect network)\r\n";

}

s = s + cd.getConnectedTypeInfo(InternetConnectionActivity.this);

showAlertDialog(InternetConnectionActivity.this, "Internet Connection", s, true);

}

};

}

源代码 下载地址

发表评论