SoFunction
Updated on 2025-03-11

Android uses JobScheduler to regularly push local notification instance code

Android 5.0 provides JobService and JobScheduler for performing a task at a later point in time or when a specific condition is met. Using JobScheduler, we can push local notifications to improve the user retention rate of the app when the user has not used our app for a period of time. Without further ado, please enter the code:

First, use the JobScheduler to schedule a job when the app's MainActivity is started. Note that in onCreate we record the time when the user starts the app in the shared preference:

@Override
protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  ().putLong(Constants.SP_PARAM_LAST_LAUNCH, ()).apply();
  scheduleNotifications();
}

private void scheduleNotifications() {
    if (.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      try {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        JobInfo jobInfo = new (1, new ComponentName(getPackageName(), ()))
            .setRequiresCharging(false)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //Any network status            .setPersisted(true) //Retain job after system restart            .setPeriodic(1000 * 60 * 60 * 24) //The unit here is milliseconds, 1000 * 60 * 60 * 24 represents one day (24 hours)            .build();
        (jobInfo);
      } catch (Exception ex) {
        ("scheduleNotifications failure");
      }
    }
  }

Then there is the NotificationService that push notifications. Here SharedPreferences is used to use dagger2 dependency injection. If you don't use dagger, you can directly obtain it:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NotificationService extends JobService {
  @DefaultSharedPref
  @Inject
  SharedPreferences sharedPreferences;

  @Override
  public boolean onStartJob(JobParameters params) {
    try {
      long lastLaunchTime = (Constants.SP_PARAM_LAST_LAUNCH, -1);
      if(lastLaunchTime > 0) {
        long intervalSinceLastLaunch = () - lastLaunchTime;
        //Check whether a certain time has passed since the user last started the app        if(intervalSinceLastLaunch > 1000 * 60 * 60 * 24) {
               mBuilder =
                  new ()
                      .setAutoCancel(true)
                      .setSmallIcon(.ic_launcher)
                      .setContentTitle("My app")
                      .setContentText("New content is online, come to our app to check it out!");
              Intent resultIntent = new Intent(, );

              TaskStackBuilder stackBuilder = ();
              ();
              (resultIntent);
              PendingIntent resultPendingIntent =
                  (
                      0,
                      PendingIntent.FLAG_UPDATE_CURRENT
                  );
              (resultPendingIntent);
              NotificationManager mNotificationManager =
                  (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
              (1, ());
        }
      }
    } catch (Exception ex) {
      ("Exception in NotificationService onStartJob");
    }
    return false;
  }

  @Override
  public boolean onStopJob(JobParameters params) {
    ("NotificationService onStopJob");
    return true;
  }
}

Finally, we need to register our service and apply for relevant permissions in Manifest:

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

  <service android:name=".NotificationService"
      android:permission=".BIND_JOB_SERVICE" />

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.