1

I am developing an android application targeting android nougat. It should do a remote sql to local database sync, if connected to internet, in background thread. I tried using broadcast receiver to detect connectivity, but it is not firing on android N. How can i do that (Check internet availability) in background? An example would be helpful

I tried this

Android manifest

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

NetworkChangeReciever.java

public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
        Toast.makeText(context,"Internet state changed",Toast.LENGTH_LONG).show();
}
Aswin P Ashok
  • 702
  • 8
  • 27
  • Check this out it might help u http://stackoverflow.com/a/42229749/5610842 – RaghavPai Feb 14 '17 at 15:30
  • How to use that class? I want to trigger some opration when user enables internet,even if my application is not active. How to monitor that? Sorry I am a noob – Aswin P Ashok Feb 15 '17 at 06:18

3 Answers3

1

I got an answer to my question.

Broadcast receiver with action <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />, which is registered in manifest will not fire in android N. But one can register a broadcast programatically and make it work. But it will not work when the app is killed.

Then in my case, I had two options (thats what I thought), Schedule the sync operation with

  • GCM Network manager

    OR

  • Job scheduler

The problem with job scheduler is that it works only above API level 21, but it doesn't need Google play service to work. On the other hand GCM Network manager had backwards compatibility, but needs google play service to run.

Then I visited Intelligent Job Scheduling, and they said, go with Firebase Job dispatcher,

Firebase JobDispatcher supports the use of Google Play services as an implementation for dispatching (running) jobs, but the library also allows you to define and use other implementations: For example, you might decide to use JobScheduler or write your own, custom code. Because of this versatility, we recommend that you use this Firebase JobDispatcher if your app targets a version of Android lower than 5.0 (API level 21).

And I took that advice, and this is what I did,

Created a service (SyncService.java) which does the sync job,

added that service to manifest

<service
    android:exported="false"
    android:name=".SyncService">
        <intent-filter>
            <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
        </intent-filter>
</service>

And in my activity, created and executed a Job to sync

Job syncJob=jobDispatcher.newJobBuilder()
            .setService(SyncService.class)
            .setRecurring(true)
            .setLifetime(Lifetime.FOREVER)
            .setRecurring(true)
            .setLifetime(Lifetime.FOREVER)
            .setTrigger(Trigger.executionWindow(3,600))
            .setConstraints(Constraint.ON_ANY_NETWORK) //does job when network is available
            .setReplaceCurrent(true)
            .setTag("syncService")
            .build();
jobDispatcher.mustSchedule(syncJob);

And this works in background.

Aswin P Ashok
  • 702
  • 8
  • 27
0
private void registerInternetReceiver()
{
    if (this.internetReceiver != null) return;
    this.internetReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive (Context context, Intent intent)
        {
            if (isInternetAvailable()) {
                Log.i ("Tag", "internet status online");
                // write ur logic here
            }
            else
                Log.i ("Tag", "internet status offline");
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction (ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver (internetReceiver, filter);
}

private boolean isInternetAvailable()
{
    try
    {
        return (Runtime.getRuntime().exec ("ping -c 1 google.com").waitFor() == 0);
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return false;
}

// Use the above code

RaghavPai
  • 652
  • 9
  • 14
  • 1
    It works when my application is active. But When I exit my app or kill it by clearing active tasks, and then connect/disconnect internet, its not working – Aswin P Ashok Feb 17 '17 at 05:32
0

Connectivity action should be used for nougat

 IntentFilter intentFilter = new IntentFilter();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)

    {
        //For Nougat
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTI‌ON);
    } else

    {
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_CHANGE));
    }

    registerReceiver(new NetworkConnectionReceiver(), intentFilter);