最近公司有个项目连接WIFI_Sd卡操作,手机在连接WIFI卡的时候,因为手机显示连接了WIFI就没法走数据了,可是WIFI卡本身没联网啊,又想在连接WIFI卡的时候,其他内容走移动数据外网,但是只能在Android6.0以上实现这功能
OkHttpClientokHttpClient=null;
public void getTestWifi(){
final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder =null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
builder =new NetworkRequest.Builder();
builder.addCapability(NET_CAPABILITY_INTERNET);
//强制使用蜂窝数据网络-移动数据
builder.addTransportType(TRANSPORT_CELLULAR);
NetworkRequest build = builder.build();
connectivityManager.requestNetwork(build,new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
try {
if(Build.VERSION.SDK_INT >=23) { connectivityManager.bindProcessToNetwork(network); //这句话要加上哈,不然设置不生效
}else{// 23后这个方法舍弃了 ConnectivityManager.setProcessDefaultNetwork(network); }String url ="http://www.baidu.com";
okHttpClient =new OkHttpClient();
final Request request =new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
Call call =okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG,"onFailure: ");
}
@Override
public void onResponse(Call call, Response response)throws IOException {
Log.d(TAG,"onResponse: " + response.body().string());
}
});
}catch (Exception e) {
}
}
}
}
网友评论