1

Below is the code which i am using to schedule job to trigger everytime i connect to internet

FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
                    Job job = dispatcher.newJobBuilder()
                    //persist the task across boots
                    .setLifetime(Lifetime.FOREVER)
                    //.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
                    //call this service when the criteria are met.
                    .setService(ScheduledJobService.class)
                    //unique id of the task
                    .setTag("UniqueTagForYourJob")
                    //don't overwrite an existing job with the same tag
                    .setReplaceCurrent(false)
                    // We are mentioning that the job is periodic.
                    .setRecurring(true)
                    // Run between 30 - 60 seconds from now.
                    .setTrigger(Trigger.executionWindow(3, 5))
                    // retry with exponential backoff
                    .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
                    //.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                    //Run this job only when the network is available.
                    .setConstraints(Constraint.ON_ANY_NETWORK)
                    .build();
                    dispatcher.mustSchedule(job);

Below is the code for ScheduleJobService which is used to trigger random notification with the current date time(just for testing purpose) when job executes

package com.labstract.lest.wallistract;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
import com.labstract.lest.wallistract.FullScreenViewSlider.FullScreenActivity;
import com.labstract.lest.wallistract.GridActivities.Image;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class ScheduledJobService extends JobService {
 @Override
 public boolean onStartJob(JobParameters job) {
  Log.d("ScheduledJobService", "Job called");
  Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_LONG).show();
  ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
   .getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
  int random = (int)(Math.random() * 50 + 1);
  if (networkInfo.isConnected()) {
   Date currentTime = Calendar.getInstance().getTime();
   Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
   NotificationCompat.Builder builders = new NotificationCompat.Builder(getApplicationContext());
   Notification notifications = builders.setContentTitle("Wallistract")
    .setContentText(currentTime.toString())
    .setAutoCancel(true)
    .setPriority(Notification.PRIORITY_HIGH)
    .setSmallIcon(R.mipmap.ic_launcher)
    .build();
   NotificationManager notificationManagers = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
   notificationManagers.notify(random, notifications);
  }
  return true;
 }


 @Override
 public boolean onStopJob(JobParameters job) {
  return false;
 }
}

My Question is What is wrong in My Code because of which it is not triggering when the phone connects to internet everytime , is it parameters in the

.setTrigger(Trigger.executionWindow(3, 5))

or

.setConstraints(Constraint.ON_ANY_NETWORK)

or

any other thing ? Please help .

Adi
  • 903
  • 2
  • 15
  • 25

1 Answers1

0

I'm not sure you're using the right tool for the job. Firebase Job Dispatcher is intended for use cases where you want to run a task every X hours / days, with requirements on charging, internet, etc.

You've described wanting to execute code every time the device connects to the internet, which Job Dispatcher isn't going to work well for. As a trivial example, if you connect + disconnect rapidly, Job Dispatcher will only run once and then assume its task is done. Additionally, very short times like the one you've listed aren't reliable.

An alternative approach for your case is to register a android.net.conn.CONNECTIVITY_CHANGE broadcast receiver in the manifest, and then be notified by the OS whenever the network state changes. This is much more reliable, and easier to implement.

This answer defines the process of setting up a broadcast receiver, and checking internet state within it. The code isn't ideal, but it's a starting point.

I've also previously created an example repository if you just want to monitor status inside the app, in a much more efficient way than the linked answer.

Jake Lee
  • 7,549
  • 8
  • 45
  • 86