private boolean isNetworkAvailable(Context con) { ConnectivityManager cm = (ConnectivityManager) con .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; NetworkInfo netinfo = cm.getActiveNetworkInfo(); if (netinfo == null) { Toast.makeText(getApplicationContext(), "网络连接失败", 1).show(); return false; } if (netinfo.isConnected()) { return true; } return false; }
返回false就是网络连接失败
返回true就是网络连接正常
以上代码可以在应用的初始化页面进行操作,为了增加用户体验,在跳转初始化页面之后弹出设置打开网络的提示框,点击联网,跳转到连接网络的页面进行设置,代码如下:
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; public class NetWorkingCheck { NetworkInfo info;// 网络测试 Context context; String str; public static boolean B=false; public NetWorkingCheck(Context context,String str) { this.str=str; this.context=context; } public void chek(){ ConnectivityManager manager = (ConnectivityManager) context .getSystemService(str); info = manager.getActiveNetworkInfo(); if (info == null) { B=true; AlertDialog.Builder builder = new Builder(context); builder.setMessage("网络连接失败,请连接您的网络!"); builder.setTitle("提示"); builder.setPositiveButton("联网", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { context.startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { SysApplication.getInstance().exit(); dialog.dismiss(); } }); builder.create().show(); } } }
然后在主页面进行调用
//连接网络
NetworkInfo info;
// 服务意图
Intent service_it;
在onCreate()的方法里调用如下
String ser = CONNECTIVITY_SERVICE; NetWorkingCheck netw = new NetWorkingCheck(this, ser); netw.chek(); if (NetWorkingCheck.B) { NetWorkingCheck.B = false; } else { // 注册广播 IntentFilter filter = new IntentFilter(); filter.addAction("com.cn.WelcomeService.receiver"); registerReceiver(receiver, filter); //requestMethod(); }
方法外
// 广播接收器 BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("com.cn.WelcomeService.receiver")) { stopService(service_it); } } }; @Override protected void onDestroy() { // TODO Auto-generated method stub if (receiver != null) { //unregisterReceiver(receiver); } super.onDestroy(); }
到此点击联网按钮,即可跳转到设置网络连接的页面。