我的代码中是否有任何错误.我正在连接wifi.
码:
public class AndroIDConnectivityActivity extends Activity{button checkBtn;/** Called when the activity is first created. */@OverrIDepublic voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.main); checkBtn = (button) findVIEwByID(R.ID.button1); checkBtn.setonClickListener(new VIEw.OnClickListener() { public voID onClick(VIEw v) { if(isInterneton()) { Toast.makeText(getBaseContext(),"Connected",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(),"Not connected",Toast.LENGTH_SHORT).show(); } }}); } public final boolean isInterneton() { ConnectivityManager connec = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING) ||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) ||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)) { return true; } else if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.disCONNECTED) || (connec.getNetworkInfo(1).getState() == NetworkInfo.State.disCONNECTED)) { return false; } return false; } }解决方法 使用下面的代码
public static boolean isInternetAvailable(Context context) { boolean isInternetAvailable = false; try { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if(networkInfo != null && (networkInfo.isConnected())) { isInternetAvailable = true; } } catch(Exception exception) { // Do nothing } return isInternetAvailable; }
并尝试真正的设备
使用Activity onCreate方法中的代码
if(isInternetAvailable(this)){Toast toast = Toast.makeText(this,"internet available",Toast.LENGTH_SHORT); toast.show();}else{Toast toast = Toast.makeText(this,"internet not available",Toast.LENGTH_SHORT); toast.show();}
必需的清单权限
<uses-permission androID:name="androID.permission.INTERNET" /> <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE" />总结
以上是内存溢出为你收集整理的在android中进行网络连接检查全部内容,希望文章能够帮你解决在android中进行网络连接检查所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)