2015-11-07 79 views
1

如何使在此背景代碼運行永遠和隨時檢測是否有網絡連接或沒有(沒有互聯網連接),並顯示出敬酒時,有沒有上網嗎?顯示敬酒的時候沒有互聯網接入的Android

here is我想要什麼(見喵MEO的答案),但它是一種用於檢測互聯網

// check connectivity (Internet access) 
    private boolean checkConnectivity() { 
     System.out.println("executeCommand"); 
     Runtime runtime = Runtime.getRuntime(); 
     try { 
      Process mIpAddrProcess = runtime 
        .exec("/system/bin/ping -c 1 8.8.8.8"); 
      int mExitValue = mIpAddrProcess.waitFor(); 
      System.out.println(" mExitValue " + mExitValue); 
      if (mExitValue == 0) { 
       img_c1.setImageResource(R.drawable.index2); 
       return true; 
      } else { 
       img_c2.setImageResource(R.drawable.index2); 
       return false; 
      } 
     } catch (InterruptedException ignore) { 
      ignore.printStackTrace(); 
      System.out.println(" Exception:" + ignore); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      System.out.println(" Exception:" + e); 
     } 
     return false; 
    } 

回答

2

首先,它的壞主意,在後臺一直運行這段代碼。

而是使用BroadCastReceiver檢查網絡狀態,所以它只會在網絡狀態變化時活躍,

你必須註冊爲BroadcastReceiver網絡狀態改變事件。所以,當設備上發生網絡android廣播事件的任何變化時,您的BroadcastReceiver將監聽該事件並基於此顯示Toast。

好的教程:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/

+0

我想用廣播接收器,但該鏈接,而有關檢測因特網連接,你能告訴我如何用我的代碼用於檢測互聯網接入(發送ping命令)在這個廣播接收器http://stackoverflow.com/questions/3767591/check-intent-internet-connection – MaggotSauceYumYum

+0

任何線索? @ user370305 – MaggotSauceYumYum

+0

爲什麼要ping到外部服務器?只是爲了檢查互聯網連接? – user370305