需要权限:
<!-- 访问网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 检测网络状态权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
package com.example.zhangying.wifidemo2;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private boolean isConnected = false;
private ConnectivityManager connectManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.得到网络连接信息
connectManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//2.判断网络是否连接
if (connectManager.getActiveNetworkInfo() != null) {
isConnected = connectManager.getActiveNetworkInfo().isConnected();
}
if (isConnected) {
//网络已经连接,判断是wifi连接还是GPRS连接
isWifiOrGPRS();
} else {
openNetWork();
}
}
private void isWifiOrGPRS() {
//获得wifi状态state
NetworkInfo.State wifi_state = connectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//获得gprs状态
NetworkInfo.State gprs_state = connectManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
if (wifi_state == NetworkInfo.State.CONNECTED || wifi_state == NetworkInfo.State.CONNECTING) {
Toast.makeText(this, "wifi open!", Toast.LENGTH_SHORT).show();
} else if (gprs_state == NetworkInfo.State.CONNECTED || gprs_state == NetworkInfo.State.CONNECTING) {
Toast.makeText(this, "gprs open!", Toast.LENGTH_SHORT).show();
}
}
private void openNetWork() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("网络连接");
builder.setMessage("当前网络不可用,请设置网络!");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
/**
* 若API>=10
*/
if (Build.VERSION.SDK_INT > 10) {
intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
} else {
/**
* 若API<10
*/
intent = new Intent();
ComponentName componentName = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(componentName);
intent.setAction("android.intent.action.VIEW");
}
startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
}