0

I want to run a service daily at 9:00 PM in the night and do some work.

I am using GcmNetworkManager class but I can't figure out on how to give the exact time and date to the PeriodicTask.

This is my GcmTaskService class

public class Sc extends GcmTaskService {
@Override
public int onRunTask(TaskParams taskParams) {
    Log.i("onRunTask: " + taskParams.getTag(), "gcm task");

    return GcmNetworkManager.RESULT_SUCCESS;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("onStartCommand", "gcm task");

    return super.onStartCommand(intent, flags, startId);

}
}

Manifest declaration

<service
        android:name=".Sc"
        android:exported="true"
        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY"/>
        </intent-filter>
    </service>

This is how I call the task

long periodSecs = 30L; // the task should be executed every 30 seconds
    long flexSecs = 15L; // the task can run as early as -15 seconds from the scheduled time

    String tag = "myScan|1";

    PeriodicTask periodic = new PeriodicTask.Builder()
            .setService(Sc.class)
            .setPeriod(periodSecs)
            .setFlex(flexSecs)
            .setTag(tag)
            .setPersisted(false)
            .setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_ANY)
            .setRequiresCharging(false)
            .setUpdateCurrent(true)
            .build();

    GcmNetworkManager.getInstance(this).schedule(periodic);

It is running perfectly fine on every 30 seconds. But how to give it an exact time to run.

WISHY
  • 11,067
  • 25
  • 105
  • 197

1 Answers1

-1
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9); for 9 am to 1o am
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

PeriodicTask periodic = new PeriodicTask.Builder()
            .setService(Sc.class)
            .setPeriod(calendar.getTimeInMillis())
            .setFlex(flexSecs)
            .setTag(tag)
            .setPersisted(false)
            .setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_ANY)
            .setRequiresCharging(false)
            .setUpdateCurrent(true)
            .build();

I never tried this but you can give a try for this.

Silvans Solanki
  • 1,267
  • 1
  • 14
  • 27
  • Please at least go through the doc before answering. "setPeriod(long periodInSeconds)" calendar.getTimeInMillis() will be so wrong. – binaryKarmic Feb 28 '18 at 13:01