[android]代码库
//创建 IntentFilter
IntentFilter filter=new IntentFilter("com.internet");
//指定广播动作
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
MyInternet myInternet=new MyInternet();
registerReceiver(myInternet,filter);
//创建广播接受者
class MyInternet extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
//获取网络管理者
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);
//获取网络信息
NetworkInfo info = manager.getActiveNetworkInfo();
if(info!=null&&info.isAvailable()){
//获取网络名称
String name = info.getTypeName();
if (info.getType()==ConnectivityManager.TYPE_WIFI){
Toast.makeText(getActivity(),"当前正在使用无线网络",Toast.LENGTH_LONG).show();
getdate();
}else
if(info.getType()==ConnectivityManager.TYPE_MOBILE){
Toast.makeText(getActivity(),"当前正在使用2G 3G 4G网络",Toast.LENGTH_LONG).show();
getdate();
}
}else{
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle("提醒");
builder.setMessage("当前网络不可用,点击确定设置网络");
builder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//跳转到系统网络设置的界面
Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.Settings");
startActivity(intent);
}
}).show();
}
}
}
}
清单文件加权限:<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
by: 发表于:2017-10-18 09:17:59 顶(0) | 踩(0) 回复
??
回复评论