Friday, June 23, 2017

Android: Job Scheduler schedule you job

June 23, 2017

Welcome to the android tutorial.
android
Android

In this post, we talk about JobSchedular. A job scheduler is more effective than alarm manager. Want to see it benefits then check out this link.

For scheduling, you have many options to use.
1. Android Alarm manager
2. Job Scheduler
3. Gcm Network Manager

In the previous post, we talk about android alarm manager. Are you confused about those? which one is appropriate for your android app. Read this document Become a pro at scheduling tasks in Android

Now come to code- Before starting we have to add below line in the build.gradle file
compile 'com.firebase:firebase-jobdispatcher:0.5.0'
Now we need to a service class. Create a services class and extend it to JobService. In this case, my class name is EverydayJobTask.java
public class EverydayJobTask extends JobService {
}
we need to override two class-
1. onStartJob()
2. onStopJob()

onStartJob() will call when the job is started. So we need to implement the start logic in this methods.
onStopJob() will call after job will finish. In my case, I show a notification on start Job.

Full Java code of service class-
public class EverydayJobTask extends JobService {

  @Override
  public boolean onStartJob(JobParameters job) {

  //if job schedule then set a notification
  TaskNotification.notify(EverydayJobTask.this,
  "Start sync Task... ", 0);

  return true;
  }

  @Override
  public boolean onStopJob(JobParameters job) {
  return true;
  }
}
Now we need to build FirebaseJobDispatcher. we need to create a google play driver
Driver driver = new GooglePlayDriver(context);
now create a firebase job dispatcher variable and pass this driver
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
next step is to create a job this job will help to do the task with time-
Job syncJob = dispatcher.newJobBuilder()
set service to the job by calling setService and parameter will be a service class and its super class must be JobService.
.setService(EverydayJobTask.class)
set a tag and this tag must be unique. this tag is used to identify this job.
.setTag("Everyday_Task")
set it's lifetime by calling setLifeTime(). setLifetime sets how long this job should persist you two option
1. UNTIL_NEXT_BOOT
2.FOREVER
.setLifetime(Lifetime.FOREVER)
set a Network constraints on which this Job should run. You have some option
1. DEVICE_CHARGING -> the will be run only while the device is running.
2. ON_ANY_NETWORK -> for this case job will be running on any network
3. ON_UNMETERED_NETWORK-> on unmetered connection.

In my case, I set on any network
.setConstraints(Constraint.ON_ANY_NETWORK)
Note: It might be a good idea to include a preference for this, as some users may not want to download any data on their mobile plan.

set trigger for the job to start by calling setTrigger and the parameter will be another method Trigger.executionWindow(). This method has two parameters.The first argument for * which the data should be synced Note: this end time is not * guaranteed, but is more of a guideline for FirebaseJobDispatcher to go off we need two time interval time and flex time for that add those below line-
private static final int HOURS = 3;
private static final int INTERVAL_SECONDS = (int) TimeUnit.HOURS.toSeconds(HOURS);
private static final int FLEXTIME_SECONDS = INTERVAL_SECONDS / 3;
Note: I set interval time three hours. If you want to set more hour then change hours variable. After that add below code-
.setTrigger(Trigger.executionWindow(INTERVAL_SECONDS,INTERVAL_SECONDS+FLEXTIME_SECONDS))
If you want to set this job requiring the set true in the setRecurring or don't set false-
.setRecurring(true)
once the job is finished then call build method. this method has returned a job.
.build();
we finished making the job. But we have one more step to finish. we need to set schedule this job with the dispatcher.
dispatcher.schedule(syncJob);

oh! we done. Now I think you can use this job scheduler in your next android project.
That's it's today post
Happy coding.

Read More

Friday, June 16, 2017

Android: Alarm Manger with broadcast receiver

June 16, 2017

Welcome to this post. In this post, we are going to learn about Alarm manager and BroadCast Receiver. As usual before start please check official documentation.
1.Alarm Manager official documentation
2.BroadCast Receiver official documentation

Alarm manager is used for scheduling task. If you want to do a task after some time intervals or if want to do some task at 11 am. of the daytime, you have to use alarm manager. Because there is a possibility that user is not using this app at that particular time. So If you are using alarm manager and schedule some task then you don't have to tense about your task is executed or not. More accurately, when phone time is 11.am (example time) then system send a broadcast and from the broadcast receiver, you can receive this signal and execute the task.

Ok, enough talk.

First Alarm Manager-

* we have to create a calendar variable like-
Calendar calendar = Calendar.getInstance();
Now set a time when you do the task. In this case, I want to set 23.59.00 this time. you can also set a specific date. But I don't need a date I just need time so I set time only. But you can also add a date in similar ways.
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,0);

Now we have to do-
 * create an alarm manager and get system alarm services
* create an Intent and Intent class must be a broadcast receiver extend the class (we will create in later in this post).
* set an intent action (so we can filter on broadcast receiver, in this case, I use package name)
* now create a pending intent and get broadcast receiver
*now set alarm manager with set repeating
see the code-
//alarm manager
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, TaskManager.class);
intent.setAction("com.blogspot.shudiptotrafder.lifeschedular");

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,

PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.setRepeating(AlarmManager.RTC_W
  AKEUP, calendar.getTimeInMillis(),
  AlarmManager.INTERVAL_DAY, pendingIntent);
Note: here I set interval time AlarmManager.INTERVAL_DAY so it will be trigger at once in every day. you can set a custom time limit.
That's it on alarm manager.

BroadCast Reciever 

the broadcast receiver receives system and custom broadcast. we also explain in the first section of this post. Create a class extend with the broadcast receiver
public class TaskManager extends BroadcastReceiver {
}
you have to override onRecive method.
@Override
public void onReceive(Context context, Intent intent) {
}
we check that if intent has the same action that we have passed through pending intent on alarm manager. If the answer is true then we do our task. For simplicity, I show a toast message.
if (intent.getAction().equalsIgnoreCase("com.blogspot.shudiptotrafder.lifeschedular")) {

  Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();
}
Now we have to declare this receiver on manifest (AndroidMenifest.xml)
<!-- Broadcast Receiver -->
<receiver
  android:name=".manager.TaskManager"
  android:enabled="true"
  android:exported="false">
  <intent-filter>
  <action android:name="com.blogspot.shudiptotrafder.lifeschedular"/>

  <category android:name="android.intent.category.DEFAULT"/>
  </intent-filter>
</receiver>
we set the specific broadcast receiver on the intent filter. If you want to receive more action then set on action tag. Full receiver class-
public class TaskManager extends BroadcastReceiver {
  
  @Override
  public void onReceive(Context context, Intent intent) {

  if (intent.getAction().equalsIgnoreCase("com.blogspot.shudiptotrafder.lifeschedular")) {

  Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();
}
That's all.
Happy coding.

Read More