遇到一个需求,想看看设备是否联网,但又没有浏览器,写个程序测一下
1.builder
html/xml
implementation 'com.github.bumptech.glide:glide:4.8.0'
2.网络权限
typescript
<!-- 获取网络状态 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
3.主界面
java
package com.example.iosdialogdemo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
public class TestActivity extends AppCompatActivity {
private boolean isConnect = false;
private boolean isConnect2 = false;
private ImageView iv_ph;
private String url = "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
isNetPingUsable();
isNetworkAvailable(TestActivity.this);
iv_ph = findViewById(R.id.iv_ph);
Glide.with(getApplicationContext()).load(url).into(iv_ph);
}
public boolean isNetPingUsable() {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("ping -c 3 www.baidu.com");
int ret = process.waitFor();
if (ret == 0) {
isConnect = true;
} else {
isConnect = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return isConnect;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) { // 当前网络是连接的
isConnect2 = info.getState() == NetworkInfo.State.CONNECTED; // 当前所连接的网络可用
Log.e("TAG", "" + isConnect2);
}
}
return isConnect2;
}
}