判斷手機的網絡狀態,需要使用ConnectivityManager。ConnectivityManager主要管理和網絡連接相關的操作 。 相關的TelephonyManager則管理和手機、運營商等的相關信息;WifiManager則管理和wifi相關的信息。NetworkInfo類包含了對wifi和mobile兩種網絡模式連接的詳細描述,通過其getState()方法獲取的State對象則代表著連接成功與否等狀態。
Java代碼:
- package com.lenovo.test.network;
-
- import Android.app.Activity;
- import android.app.AlertDialog;
- import android.app.AlertDialog.Builder;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo.State;
- import android.os.Bundle;
- import android.provider.Settings;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class JudgeNetworkActivity extends Activity {
- /** Called when the activity is first created. */
- private Button mButton = null;
- private TextView mTextView = null;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- mButton = (Button) findViewById(R.id.mbutton);
- mTextView = (TextView) findViewById(R.id.mtv);
- final Builder builder = new AlertDialog.Builder(this);
- mButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- // TODO Auto-generated method stub
- ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
-
- // mobile 3G Data Network
- State mobile = conMan.getNetworkInfo(
- ConnectivityManager.TYPE_MOBILE).getState();
-
- // wifi
- State wifi = conMan.getNetworkInfo(
- ConnectivityManager.TYPE_WIFI).getState();
- mTextView.setText("Moble Network:" + mobile.toString() + "\n"
- + "WIFI Network:" + wifi.toString());
- // 如果3G網絡和wifi網絡都未連接,且不是處於正在連接狀態 則進入Network Setting界面 由用戶配置網絡連接
- if (!(mobile == State.CONNECTED || mobile == State.CONNECTING
- || wifi == State.CONNECTED || wifi == State.CONNECTING)) {
- builder.setTitle("Message")
- .setMessage("沒有可用的網絡,請設置有效的網絡連接!")
- .setNegativeButton("確定",
- new DialogInterface.OnClickListener() {
- public void onClick(
- DialogInterface dialog,
- int which) {
- startActivity(new Intent(
- Settings.ACTION_WIRELESS_SETTINGS));// 進入無線網絡配置界面
- // startActivity(new
- // Intent(Settings.ACTION_WIFI_SETTINGS));
- // 進入手機中的wifi網絡設置界面
- }
- }).show();
- }
- }
- });
- }
- }
在AndroidManifest.xml裡添加權限:
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
運行結果: