public static boolean isConnect(Context context) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
try {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
// 获取网络连接管理的对象
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null&& info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
// TODO: handle exception
Log.v("error",e.toString());
}
return false;
}
最后一点还得再manifest中添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
网络没信号的时候,直接跳转到网络设置界面
Setting的源代码是在AndroidManifest.xml中设置的
写在<application>标签里,如下:
- <PreferenceScreen
- android:title="@string/radio_controls_title"
- android:summary="@string/radio_controls_summary">
- <intent
- android:action="android.intent.action.MAIN"
- android:targetPackage="com.android.settings"
- android:targetClass="com.android.settings.WirelessSettings" />
- </PreferenceScreen>
然后在对应的Activity中写如下的java代码:
- Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
- startActivity(wifiSettingsIntent);
public static void showNetErrorDialog(final Context ctx) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setMessage("没有网络,前去打通?").setIcon(R.drawable.ic_launcher)
.setCancelable(true);
builder.setPositiveButton("前往", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent wifiSettingsIntent = new Intent(
"android.settings.WIFI_SETTINGS");
ctx.startActivity(wifiSettingsIntent);
}
});
builder.setNegativeButton("拉倒", null);
builder.create().show();
}
if (appContext.isNetworkConnected(getActivity())) {
LoadJournalAsyncTask loadJournal = new LoadJournalAsyncTask();
loadJournal.execute(0, null);
} else {
DialogUtil.showNetErrorDialog(getActivity());
}