Android检测手机或PAD是否连网

1. 引言

 

    在进行Android手机或PAD的网络开发过程中,检测是否已经连接互连网是必不可少的一步,下面介绍其代码实现。

 

2. 功能实现

 

    (1) 主布局(main.xml)实现:<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > <Button android:id = "@+id/checkNetWork" android:text = "检测网络" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout>

 

    (2) 主Activity实现:package com.flora; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class NetWorkActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button checkNetWork = (Button) findViewById(R.id.checkNetWork); checkNetWork.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (checkNetWorkStatus()) { Toast.makeText(NetWorkActivity.this, "连接成功!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(NetWorkActivity.this, "连接失败!", Toast.LENGTH_SHORT).show(); } } }); } private boolean checkNetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } return netSataus; } }

你可能感兴趣的:(android,service,layout,手机,button,encoding)