Android设备判断网络连接状态
2018-07-20 来源:open-open
所需权限(AndroidManifest.xml文件中添加):
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Java代码(MainActivity.java文件)
package com.example.androidtest; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); boolean bFlag = isNetworkAvailable(this.getApplicationContext()); if (bFlag) { Log.i("Network state - ", "connected"); } else { Log.i("Network state - ", "disconnected"); } } /** * 判断网络连接状况 * * @param ctx * @return */ public boolean isNetworkAvailable(Context ctx) { boolean bFlag = false; if (ctx != null) { ConnectivityManager conMan = (ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE); if (conMan != null) { // wifi Network NetworkInfo nInfoW = conMan .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (nInfoW != null) { State wifi = nInfoW.getState(); if (State.CONNECTED == wifi) { bFlag = true; } } if (!bFlag) { // mobile Network NetworkInfo nInfoM = conMan .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (nInfoM != null) { State mobile = nInfoM.getState(); if (State.CONNECTED == mobile) { bFlag = true; } } } } } return bFlag; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
isNetworkAvailable方法里先做wifi连接状态判断,如果wifi未连接,再做2g/3g/4g...手机网连接状态判断。
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐