首页 > 代码库 > Android 网络状态检测
Android 网络状态检测
package com.example.administrator.yunstore.net; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.example.administrator.yunstore.R; /** * Created by Administrator on 2016/10/20. */ public class CheckNetException{ private ConnectivityManager connectivityManager; private Context context; public CheckNetException(Context context){ this.context=context; } /** * @return 网络是否连接 */ public boolean checkNetConn() { //得到网络链接管理器 connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //获取网络链接信息 NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //判断网络是否链接 if (activeNetworkInfo != null) { if (activeNetworkInfo.isConnected()) { return true; } else { return false; } } return false; } /** * 设置wifi */ public void setNetWork(){ AlertDialog.Builder alert=new AlertDialog.Builder(context); alert.setIcon(R.drawable.set); alert.setTitle("网络提示信息"); alert.setMessage("网络不可用,如果继续,请先设置网络!"); alert.setPositiveButton("设置网络", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = null; /** * 判断手机系统的版本!如果API大于10 就是3.0+ * 因为3.0以上的版本的设置和3.0以下的设置不一样,调用的方法不同 */ if (android.os.Build.VERSION.SDK_INT > 10) { intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS); } else { intent = new Intent(); ComponentName component = new ComponentName( "com.android.settings", "com.android.settings.WirelessSettings"); intent.setComponent(component); intent.setAction("android.intent.action.VIEW"); } context.startActivity(intent); } }); alert.setNegativeButton("暂不设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alert.create(); alert.show(); } /** * 判断网络为GPRS还是WIFI * 返回1:GPRS; * 返回2:WiFi; * 返回3:error; */ public int judgeNew(){ NetworkInfo.State gprs = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); NetworkInfo.State wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); if(gprs == NetworkInfo.State.CONNECTED || gprs == NetworkInfo.State.CONNECTING){ // Toast.makeText(context, "This is gprs", Toast.LENGTH_SHORT).show(); return 1; } if(wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING){ //Toast.makeText(context, "This is wifi", Toast.LENGTH_SHORT).show(); return 2; } return 3; } }
Android 网络状态检测
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。