摘要:在发送任何HTTP请求前最好检查下网络连接状态,这样可以避免异常。这个教程将会介绍怎样在你的应用中检测网络连接状态。File-˃New-˃AndroidProject2.创建新项目后的第一步是要在AndroidManifest.xml文件中添加必要的权限。为了访问网络我们需要INTERNET权限为了检查网络状态我们需要ACCESS_NETWORK_STATE权限AndroidManifest.xml012728293.创建一个新的类,名为ConnectionDetector.java,并输入以下代码。只要按下这个按钮就会弹出一个alertdialog显示网络连接状态。在下面的代码中我用一个alertdialog来显示预期的状态信息。
在发送任何HTTP请求前最好检查下网络连接状态,这样可以避免异常。这个教程将会介绍怎样在你的应用中检测网络连接状态。
创建新的项目
1.在Eclipse IDE中创建一个新的项目并把填入必须的信息。File->New->Android Project
2.创建新项目后的第一步是要在AndroidManifest.xml文件中添加必要的权限。
- 为了访问网络我们需要INTERNET权限
- 为了检查网络状态我们需要ACCESS_NETWORK_STATE权限
AndroidManifest.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < manifest xmlns:android = "http://schemas.android.com/apk/res/android" |
03 |
package = "com.example.detectinternetconnection" |
04 |
android:versionCode = "1" |
05 |
android:versionName = "1.0" > |
07 |
< uses-sdk android:minSdkVersion = "8" /> |
10 |
android:icon = "@drawable/ic_launcher" |
11 |
android:label = "@string/app_name" > |
13 |
android:name = ".AndroidDetectInternetConnectionActivity" |
14 |
android:label = "@string/app_name" > |
16 |
< action android:name = "android.intent.action.MAIN" /> |
18 |
< category android:name = "android.intent.category.LAUNCHER" /> |
23 |
<!-- Internet Permissions --> |
24 |
< uses-permission android:name = "android.permission.INTERNET" /> |
26 |
<!-- Network State Permissions --> |
27 |
< uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" /> |
3.创建一个新的类,名为ConnectionDetector.java,并输入以下代码。
ConnectionDetector.java
01 | package com.example.detectinternetconnection; |
03 | import android.content.Context; |
04 | import android.net.ConnectivityManager; |
05 | import android.net.NetworkInfo; |
07 | public class ConnectionDetector { |
09 |
private Context _context; |
11 |
public ConnectionDetector(Context context){ |
12 |
this ._context = context; |
15 |
public boolean isConnectingToInternet(){ |
16 |
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); |
17 |
if (connectivity != null ) |
19 |
NetworkInfo[] info = connectivity.getAllNetworkInfo(); |
21 |
for ( int i = 0 ; i < info.length; i++) |
22 |
if (info[i].getState() == NetworkInfo.State.CONNECTED) |
4.当你需要在你的应用中检查网络状态时调用isConnectingToInternet()函数,它会返回true或false。
1 | ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); |
3 | Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false |
5.在这个教程中为了测试我仅仅简单的放置了一个按钮。只要按下这个按钮就会弹出一个 alert dialog 显示网络连接状态。
6.打开 res/layout 目录下的 main.xml 并创建一个按钮。
main.xml
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
02 | < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 |
android:layout_width = "fill_parent" |
04 |
android:layout_height = "fill_parent" |
05 |
android:orientation = "vertical" > |
08 |
android:layout_width = "fill_parent" |
09 |
android:layout_height = "wrap_content" |
10 |
android:text = "Detect Internet Status" /> |
12 |
< Button android:id = "@+id/btn_check" |
13 |
android:layout_height = "wrap_content" |
14 |
android:layout_width = "wrap_content" |
15 |
android:text = "Check Internet Status" |
16 |
android:layout_centerInParent = "true" /> |
7.最后打开你的 MainActivity 文件并粘贴下面的代码。在下面的代码中我用一个 alert dialog 来显示预期的状态信息。
01 | package com.example.detectinternetconnection; |
03 | import android.app.Activity; |
04 | import android.app.AlertDialog; |
05 | import android.content.Context; |
06 | import android.content.DialogInterface; |
07 | import android.os.Bundle; |
08 | import android.view.View; |
09 | import android.widget.Button; |
11 | public class AndroidDetectInternetConnectionActivity extends Activity { |
13 |
// flag for Internet connection status |
14 |
Boolean isInternetPresent = false ; |
16 |
// Connection detector class |
20 |
public void onCreate(Bundle savedInstanceState) { |
21 |
super .onCreate(savedInstanceState); |
22 |
setContentView(R.layout.main); |
24 |
Button btnStatus = (Button) findViewById(R.id.btn_check); |
26 |
// creating connection detector class instance |
27 |
cd = new ConnectionDetector(getApplicationContext()); |
30 |
* Check Internet status button click event |
32 |
btnStatus.setOnClickListener( new View.OnClickListener() { |
35 |
public void onClick(View v) { |
38 |
isInternetPresent = cd.isConnectingToInternet(); |
40 |
// check for Internet status |
41 |
if (isInternetPresent) { |
42 |
// Internet Connection is Present |
44 |
showAlertDialog(AndroidDetectInternetConnectionActivity. this , "Internet Connection" , |
45 |
"You have internet connection" , true ); |
47 |
// Internet connection is not present |
48 |
// Ask user to connect to Internet |
49 |
showAlertDialog(AndroidDetectInternetConnectionActivity. this , "No Internet Connection" , |
50 |
"You don't have internet connection." , false ); |
59 |
* Function to display simple Alert Dialog |
60 |
* @param context - application context |
61 |
* @param title - alert dialog title |
62 |
* @param message - alert message |
63 |
* @param status - success/failure (used to set icon) |
65 |
public void showAlertDialog(Context context, String title, String message, Boolean status) { |
66 |
AlertDialog alertDialog = new AlertDialog.Builder(context).create(); |
68 |
// Setting Dialog Title |
69 |
alertDialog.setTitle(title); |
71 |
// Setting Dialog Message |
72 |
alertDialog.setMessage(message); |
74 |
// Setting alert dialog icon |
75 |
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail); |
78 |
alertDialog.setButton( "OK" , new DialogInterface.OnClickListener() { |
79 |
public void onClick(DialogInterface dialog, int which) { |
83 |
// Showing Alert Message |
运行并测试下你的程序吧!你将会得到类似下面的结果。