gpt4 book ai didi

android - 在 Android 中,在进行 HTTP 调用之前测试 Internet 是否正常工作的最佳方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 16:41:25 27 4
gpt4 key购买 nike

我正在使用 isConnected() 方法来测试互联网是否正常工作,但是,当移动数据打开但网络不工作时(旅行时发生)或Wifi 已打开但未连接到互联网,该方法返回 true 并且我的应用程序崩溃了。

我做了一些调查,发现我还需要 ping Google所以我尝试使用 internetConnectionAvailable(1000)。即使 Internet 工作正常,此方法有时也会返回 false。谁能帮我提供更好的解决方案?

 //Check device has Internet connection
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else {
//Custom Toast method
showToast("Unable to connect to Internet !");
return false;
}
}

//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
@Override
public InetAddress call() {
try {

return InetAddress.getByName("www.google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
Log.e("Google",String.valueOf(inetAddress));
return inetAddress!=null && !inetAddress.equals("");
}

最佳答案

检查互联网是否已连接...如果是,则调用 androidTask()。

 if (haveNetworkConnection()) {
new androidTask().execute();
} else {
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
}

haveNetworkConnection()的调用方法:

 public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}

方法包含HTTP请求:

 class androidTask extends AsyncTask<Void, Void, String> {
String BASE_URL = http://abc.def.com/";

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(Void... params) {

HttpURLConnection con = null;
InputStream is = null;

hashMapPost.put("report", "users");

try {
con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.connect();
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(hashMapPost));
writer.flush();
writer.close();
os.close();
buffer = new StringBuffer();
int responseCode = con.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
is.close();
}
con.disconnect();
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Throwable t) {
}
try {
if (con != null) {
con.disconnect();
}
} catch (Throwable t) {
}
}
return null;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

}
}

关于android - 在 Android 中,在进行 HTTP 调用之前测试 Internet 是否正常工作的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849211/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com