public class NetworkDetector {
public static boolean detect(Activity act) {
ConnectivityManager manager = (ConnectivityManager) act
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
TelephonyManager mTelephony = (TelephonyManager) act
.getSystemService(act.TELEPHONY_SERVICE);
// 检查网络连接,如果无网络可用,就不需要进行连网操作等
NetworkInfo info = manager.getActiveNetworkInfo();
if (info == null || !manager.getBackgroundDataSetting()) {
return false;
}
// 判断网络连接类型,只有在3G或wifi里进行一些数据更新。
int netType = info.getType();
int netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
return info.isConnected();
} else if (netType == ConnectivityManager.TYPE_MOBILE
&& netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
&& !mTelephony.isNetworkRoaming()) {
return info.isConnected();
} else {
return false;
}
}
public static void setNetworkMethod(final Activity activty) {
// 提示对话框
AlertDialog.Builder builder = new Builder(activty);
builder.setTitle("网络设置提示")
.setMessage("网络连接不可用,是否进行设置?")
.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = null;
// 判断手机系统的版本 即API大于10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(
android.provider.Settings.ACTION_WIRELESS_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");
}
activty.startActivity(intent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);boolean networkState = NetworkDetector.detect(MainActivity.this);if (!networkState) {NetworkDetector.setNetworkMethod(this);} else {Toast.makeText(MainActivity.this, "网络畅通!", Toast.LENGTH_SHORT).show();}}