[英]cordova-android & phonegap - check from Java if there is Internet available
[英]How to check internet available in Android?
我創建了一個類來檢查可用於將字符串上傳到服務器的Internet。
我的應用程序在日志cat中沒有顯示任何錯誤或警告。 所以,我不能發布任何日志。
但是當我連接或未連接到互聯網時,它始終顯示消息: You do not connect to the internet.
在else子句中。
當我調試到isInternetAvailable
方法時,它轉到第一行:
InetAddress ipAddr = InetAddress.getByName("google.com");
之后,它拋出異常,如:
cause = {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();
}
除了上面的代碼之外,還要將它添加到清單中:( 來自下面的評論)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ping一些東西會更好。 您可以使用AndroidNetworkTools 。 該庫有關於ping的良好文檔。
我檢查這樣的連接:
public boolean isDeviceOnline() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected();
}
但是,可能會發生設備已連接,但實際上無法訪問互聯網(例如,在用戶需要接受條款和條件的網絡中)。 在這種情況下,您只需發出服務器請求,然后檢查網絡響應以了解失敗的原因。
InetAddress.getByName
可以返回與空字符串不同的null
,這就是從isInternetAvailable()
獲得TRUE
的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.