How can I detect that connection was lost?

时间:2017-08-04 12:26:01

标签: android firebase firebase-realtime-database

I'm using Firebase. Some features of my app can't using was offline (or maybe offline mode can make in future). So how I can detect of connection was lost, or wifi/otherNetwork is off while running activity. I following this doc but only use when start app... not working on running app. So you guys any solution for my problem ?

1 个答案:

答案 0 :(得分:0)

Use this method to check the internet connection in the app:

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;
        }

    }

Register the reciever in the manifest file like this:

<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>

use this method in the activity where you want to check the connection:

 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);

}

Also add the permission in the menifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
相关问题