2017-08-04 87 views
-3

我正在使用Firebase。我的應用無法使用的某些功能處於脫機狀態(或者將來可能會使用離線模式)。所以如何檢測連接丟失,或者在運行活動時wifi/otherNetwork關閉。我遵循這doc,但只有當啓動應用程序...不工作的應用程序正在運行。所以你們爲我的問題提供任何解決方案?如何檢測連接丟失?

回答

0

使用此方法來檢查應用程序的互聯網連接:

public class NetworkChangeReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(final Context context, final Intent intent) { 

     Intent networkStateIntent = new Intent(Constants.NETWORK_AVAILABLE_ACTION); 
     networkStateIntent.putExtra(Constants.IS_NETWORK_AVAILABLE, isConnectedToInternet(context)); 
     LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent); 
    } 

    public boolean isConnectedToInternet(Context context) { 

     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     //should check null because in airplane mode it will be null 
     if (netInfo != null && netInfo.isConnected()) { 
      return true; 
     } else { 
      return false; 
     } 

    } 

註冊reciever清單文件是這樣的:

<receiver android:name=".utils.NetwrokConnection.NetworkChangeReceiver"> 
      <intent-filter> 
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
       <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> 
      </intent-filter> 
     </receiver> 

使用這種方法在活動中要檢查連接:

public void networkConnection() { 
     IntentFilter intentFilter = new IntentFilter(Constants.NETWORK_AVAILABLE_ACTION); 
     LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       boolean isNetworkAvailable = intent.getBooleanExtra(Constants.IS_NETWORK_AVAILABLE, false); 
       Dialogs.getInstance().showSnackbar(activity,(View) rootlayout, isNetworkAvailable); 
      } 
     }, intentFilter); 

}

同時在menifest文件中添加權限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />