0

I don't know whether this is a basic question or not.

Let us say there is an activity / fragment is in foreground. There is no internet connection while onCreate() / onViewCreate() called.

Then, how to keep checking internet connection background and parse data when internet is available when Activity / fragment is in foreground state?

Apologies if anything is incorrect. Thanks in advance

Eswar
  • 199
  • 1
  • 13

3 Answers3

0

Listen to connectivity change with Androids networkCallBack:

https://developer.android.com/reference/android/net/ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest,%20android.net.ConnectivityManager.NetworkCallback)

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

connectivityManager.registerNetworkCallback(
            new NetworkRequest.Builder().build(), 
            new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            // ...
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            // ...
        }

});
JakeB
  • 2,043
  • 3
  • 12
  • 19
  • - Can we use this in onCreateView() in fragment ? If not - which is the best place to register network callback? – Eswar Sep 09 '19 at 06:23
  • If you only intend for this function to be alive during the lifecycle of the fragment then yes, you could put it there. Otherwise a ```Service``` could serve the entire apps lifecycle. – JakeB Sep 09 '19 at 06:37
  • if i put it in onCreateView(), it is being called repeatedly. how can i overcome that? for instance - the API call has done while onViewCreated(). if network lost and connected again - same API has been called. – Eswar Sep 09 '19 at 06:47
  • Run it as a Service and check to see if the service is already running when it might be called initiated. https://developer.android.com/guide/components/services – JakeB Sep 09 '19 at 06:59
0

For handling stuff in Background

You can check internet connectivity in background using WorkManager (Part of Android Jetpack) or Android-Job these are the best libraries for handling jobs in background.

WorkManageris a new architecture component from Google and tries to solve a very similar problem this library tries to solve: implementing background jobs only once for all Android versions.

Android-Job is a utility library for Android to run jobs delayed in the background.

For handling stuff in Foreground

You can do with LifeCycle or find example in Inconvertible types; cannot cast android.app.Application error?

Modi Harsh
  • 555
  • 4
  • 7
0

First, create a class called NetworkChangeReceiver like so:

public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if ( activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            Toast.makeText(context, "Network is back", Toast.LENGTH_SHORT).show();
        }
    }
}

This class will get notified each time there is a change in the network and the code in the onReceive function checks if we are online.

next,

In your Manifest add <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> and tell Android you want to filter these kinds of events.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

next register for these events in your main activity

 private BroadcastReceiver mNetworkReceiver;
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNetworkReceiver = new NetworkChangeReceiver();
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetworkReceiver);
    }
Itamar Kerbel
  • 2,508
  • 1
  • 22
  • 29