判断手机的网络状态,需要使用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"/>运行结果: