Android网络连接状态

  categories:android资料  author:

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

 

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

本文创建一个项目演示如何检查网络状况, 界面如下:

wps_clip_image-3301

检查到有网络连接后:

wps_clip_image-23843

检查到网络没有连接的情况如下:

wps_clip_image-6004

创建新的项目

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

创建完项目结构如下:

wps_clip_image-9298

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.check”

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.check.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.check;

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;

}

}

InternetConnectionActivity.java

/*

* Copyright (C) 2010 network authors

*

* @author shao

*

* @date 2013.9.21

*

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

*

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

*

*/

package cn.iigrowing.android.network.check;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.os.Bundle;

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

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

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

// 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) {

// get Internet status

isInternetPresent = cd.isConnectingToInternet();

// check for Internet status

if (isInternetPresent) {

// Internet Connection is Present

// make HTTP requests

showAlertDialog(InternetConnectionActivity.this,

“Internet Connection”,

“You have internet connection”,

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.”,

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();

}

}

 

源代码 下载地址



快乐成长 每天进步一点点      京ICP备18032580号-1