2017-09-29 27 views
0

當從Service調用NetworkInfo.isConnectedOrConnecting()時,會面臨奇怪的行爲。儘管手機已連接到網絡,但它僅返回false。從活動和片段中,此片段按預期工作。NetworkInfo.isConnectedOrConnecting()在服務中返回FALSE

public boolean isOnline() { 
    if (mContext == null) { 
     return false; 
    } 

    NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo(); 
    return netInfo != null && netInfo.isConnectedOrConnecting(); 
} 

任何人都遇到過這個問題?也許還有另一種檢查服務內部網絡連接的方法。

+0

請添加設備型號和Android版本。 –

+0

@cgomezmendez,在手機上試用Nexus 5x Android 8.0和仿真器Nexus 5 Android 6.0 – AnZ

+0

它返回false,因爲netinfo == null或因爲netInfo.isConnectedOrConnecting爲false? –

回答

1

在你的服務類中試試類似這樣的東西。

public boolean isOnline(Context context) { 
    ConnectivityManager manager = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (manager == null) { 
     return false; 
    } 
    NetworkInfo networkInfo = manager.getActiveNetworkInfo(); 
    if (networkInfo != null){ 
     if (networkInfo.isConnectedOrConnecting()) { 
      return true; 
     } 
    } 
    return false; 
} 

編輯:利用上下文來單:

public class ServiceContextManager { 
    private static ServiceContextManager instance; 

    public static ServiceContextManager getInstance(Context context) { 
     if (instance == null) { 
      instance = new ServiceContextManager(context.getApplicationContext()); 
     } 

     return instance; 
    } 

    private Context mContext; 

    private ServiceContextManager(Context context) { 
     mContext = context; 
    } 
} 
+0

已經試過了。兩者都不起作用...... – AnZ

+0

這裏的問題是我們不知道上下文來自哪裏,並且特別是在服務上持有該對象的引用並不安全。使用單身。 – codeFreak

+0

檢查我更新的答案。 – codeFreak

1

我用的是確切的代碼,並面臨着同樣的問題,直到昨天,當我發現更好的東西。它可能看起來像不同,但這真的很好,因爲它還檢查是否有工作的互聯網連接或不作爲isNetworkConnected()將返回true的情況下連接的WiFi沒有互聯網,所以你可以使用此代碼。

public boolean isOnline() throws InterruptedException, IOException 
    { 
     String command = "ping -c 1 google.com"; 
     return (Runtime.getRuntime().exec (command).waitFor() == 0); 
    } 

您還可以將google.com更改爲任何網站,因爲google.com可能在某些國家/地區停用。
我在一個活動中使用這個而不是服務,但它會工作。

+0

該解決方案有效,但會凍結該線程。有時太久.. – AnZ

+0

@AnZ我正在使用它,有時連接可能太慢,但沒有面臨任何問題。你怎麼能這麼肯定,凍結是因爲這個? –

+0

對於一些不依賴執行速度的情況,這可能是可以應用的。但那不是我的情況。替代方案的解決方案很好。 – AnZ