我创建了一个类来检查可用于将字符串上传到服务器的互联网。
我的应用程序在日志 cat 中没有显示任何错误或警告。所以,我不能发布任何日志。
但当我连接或未连接到互联网时,它总是显示消息:您没有连接到互联网。
在 else 子句中。
当我调试到 isInternetAvailable
方法时,它转到第一行:
InetAddress ipAddr = InetAddress.getByName("google.com");
之后,它抛出如下异常:
原因 = {NetworkOnMainThreadException} "android.os.NetworkOnMainThreadException"
并返回 false。
下面的代码显示检查互联网可用,类中的所有代码 extends BroadcastReceiver
:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
@Override
public void onReceive(final Context context, final Intent intent) {
String textToServer = "text example";
if(isInternetAvailable()){
sendToServer(context, textToServer.toString());
} else {
Toast.makeText(context, "You not connect to internet.", Toast.LENGTH_LONG).show();
}
}
public void sendToServer(final Context context, final String text){
contact = new AddContactActivity();
new Thread(new Runnable() {
@Override
public void run() {
try {
String textparam = "text1=" + URLEncoder.encode(text, "UTF-8");
URL scripturl = new URL(scripturlstring);
HttpURLConnection connection = (HttpURLConnection) scripturl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setFixedLengthStreamingMode(textparam.getBytes().length);
OutputStreamWriter contentWriter = new OutputStreamWriter(connection.getOutputStream());
contentWriter.write(textparam);
contentWriter.flush();
contentWriter.close();
InputStream answerInputStream = connection.getInputStream();
final String answer = getTextFromInputStream(answerInputStream);
if(answer!="") {
String[] contactInfo = answer.split(":::::");
if(!contactExists(context, contactInfo[1])) {
contact.insertContact(context, contactInfo[0], contactInfo[1], contactInfo[2], contactInfo[3], contactInfo[4]);
} else {
return;
}
}
answerInputStream.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
最佳答案
下面的代码检查是否连接到互联网
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
除了上面的代码之外,将此添加到 list 中:(来自下面的评论)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
关于java - 如何检查 Android 中可用的互联网?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36268948/