使用广播进行网络判断
public class MainActivity extends AppCompatActivity{
private LinstenerNewWorkBroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeUtil.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_main);
//动态注册广播,创建一个IntentFilter
broadcastReceiver = new LinstenerNewWorkBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//注册
registerReceiver(broadcastReceiver, filter);
}
//接收网络状态的改变
public class LinstenerNewWorkBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
//如果能走到这,说明网络已经发生变化
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
if (ConnectivityManager.TYPE_WIFI == activeNetworkInfo.getType()) {
Toast.makeText(MainActivity.this, "wifi可用,下载吧", Toast.LENGTH_SHORT).show();
} else if (connectivityManager.TYPE_MOBILE == activeNetworkInfo.getType()) {
Toast.makeText(MainActivity.this, "现在是移动网络,当心", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "网络不可用,请检查网络", Toast.LENGTH_SHORT).show();
}
} else {
showSettingNetWorkDialog();
}
}
}
}
//网络设置对话框
private void showSettingNetWorkDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("没有设置网络,请您设置网络!!!");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//跳转网络设置界面 隐士意图
Intent intent = new Intent();
intent.setAction(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("取消", null);
builder.create().show();
}
//销毁方式
@Override
protected void onDestroy() {
super.onDestroy();
//解注册
unregisterReceiver(broadcastReceiver);
}
}