展会信息港展会大全

怎样检查获取Android网络连接状态
来源:互联网   发布日期:2016-01-14 11:28:24   浏览:1971次  

导读:在发送任何HTTP请求前最好检查下网络连接状态,这样可以避免异常。这个教程将会介绍怎样在你的应用中检测网络连接状态。创建新的项目1.在Eclipse IDE中创建一个新的项目并把填入必须的信息。 File-New-Andro......

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

创建新的项目

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

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

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

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

AndroidManifest.xml01

02

03 package="com.example.detectinternetconnection"

04 android:versionCode="1"

05 android:versionName="1.0" >

06

07

08

09

10 android:icon="@drawable/ic_launcher"

11 android:label="@string/app_name" >

12

13 android:name=".AndroidDetectInternetConnectionActivity"

14 android:label="@string/app_name" >

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

3.创建一个新的类,名为ConnectionDetector.java,并输入以下代码。

ConnectionDetector.java

01package com.example.detectinternetconnection;

02

03import android.content.Context;

04import android.net.ConnectivityManager;

05import android.net.NetworkInfo;

06

07public class ConnectionDetector {

08

09 private Context _context;

10

11 public ConnectionDetector(Context context){

12 this._context = context;

13 }

14

15 public boolean isConnectingToInternet(){

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

17 if (connectivity != null)

18 {

19 NetworkInfo[] info = connectivity.getAllNetworkInfo();

20 if (info != null)

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

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

23 {

24 return true;

25 }

26

27 }

28 return false;

29 }

30}

4.当你需要在你的应用中检查网络状态时调用isConnectingToInternet()函数,它会返回true或false。1ConnectionDetector cd = newConnectionDetector(getApplicationContext());

2

3Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false

5.在这个教程中为了测试我仅仅简单的放置了一个按钮。只要按下这个按钮就会弹出一个 alert dialog 显示网络连接状态。

6.打开 res/layout 目录下的 main.xml 并创建一个按钮。

main.xml01

02

03 android:layout_width="fill_parent"

04 android:layout_height="fill_parent"

05 android:orientation="vertical" >

06

07

08 android:layout_width="fill_parent"

09 android:layout_height="wrap_content"

10 android:text="Detect Internet Status" />

11

1213 android:layout_height="wrap_content"

14 android:layout_width="wrap_content"

15 android:text="Check Internet Status"

16 android:layout_centerInParent="true"/>

17

18

7.最后打开你的 MainActivity 文件并粘贴下面的代码。在下面的代码中我用一个 alert dialog 来显示预期的状态信息。01package com.example.detectinternetconnection;

02

03import android.app.Activity;

04import android.app.AlertDialog;

05import android.content.Context;

06import android.content.DialogInterface;

07import android.os.Bundle;

08import android.view.View;

09import android.widget.Button;

10

11public class AndroidDetectInternetConnectionActivity extends Activity {

12

13 // flag for Internet connection status

14 Boolean isInternetPresent = false;

15

16 // Connection detector class

17 ConnectionDetector cd;

18

19 @Override

20 public void onCreate(Bundle savedInstanceState) {

21 super.onCreate(savedInstanceState);

22 setContentView(R.layout.main);

23

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

25

26 // creating connection detector class instance

27 cd = new ConnectionDetector(getApplicationContext());

28

29 /**

30 * Check Internet status button click event

31 * */

32 btnStatus.setOnClickListener(new View.OnClickListener() {

33

34 @Override

35 public void onClick(View v) {

36

37 // get Internet status

38 isInternetPresent = cd.isConnectingToInternet();

39

40 // check for Internet status

41 if (isInternetPresent) {

42 // Internet Connection is Present

43 // make HTTP requests

44 showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",

45 "You have internet connection", true);

46 } else {

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

51 }

52 }

53

54 });

55

56 }

57

58 /**

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)

64 * */

65 public voidshowAlertDialog(Context context, String title, String message, Boolean status) {

66 AlertDialog alertDialog = newAlertDialog.Builder(context).create();

67

68 // Setting Dialog Title

69 alertDialog.setTitle(title);

70

71 // Setting Dialog Message

72 alertDialog.setMessage(message);

73

74 // Setting alert dialog icon

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

76

77 // Setting OK Button

78 alertDialog.setButton("OK", newDialogInterface.OnClickListener() {

79 public void onClick(DialogInterface dialog, int which) {

80 }

81 });

82

83 // Showing Alert Message

84 alertDialog.show();

85 }

86}

运行并测试下你的程序吧!

赞助本站

人工智能实验室

相关热词: 网络连接状态

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港