1

I have an app that the MainActivity has a method (called doUpdate()) that is called from a button hit. This uses the MainActivity's public variables to access a database, perform some updates, and update some records. This works well.

We now need to automate this with a PeriodicTask as well.

I created a GCMTaskManager service as follows:

public class MyPeriodicTaskService extends GcmTaskService {
  public MyPeriodicTaskService() {
  }

  @Override
  public int onRunTask(TaskParams taskParams) {
    Log.i("MYLOG","Task Running...");
    return 0;
  }
}

In my MainActivity, onCreate(), I setup the PeriodicTask as follows:

 GcmNetworkManager networkManager=GcmNetworkManager.getInstance(this);
 PeriodicTask task=new PeriodicTask.Builder()
    .setService(MyPeriodicTaskService.class)
    .setPeriod(60)
    .setFlex(30)
    .setRequiresCharging(true)
    .setTag("UpdateSchedule")
    .build();
 networkManager.schedule(task);

By watching the LOG, I know that the onRunTask() fires periodically as I hoped.

Now I need to call my MainActivity method... doUpdate(). Because this method is declared PUBLIC VOID and not STATIC, I can't call it from the services doRunTask(). If I attempt to make it a STATIC PUBLIC VOID then the MainActivity variables can't be accessed properly as needed for the internal processing steps.

How do I get around this... any recommendations?

Nick Friskel
  • 2,369
  • 2
  • 20
  • 33
Peter
  • 427
  • 4
  • 14
  • Use localbroadcastmanager or use binder/messenger for communication. Here is a sample code with explanation - https://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample – Keyur Thumar May 08 '17 at 02:33
  • Is one method better than the other (or simpilier)? I just need to "run" the doUpdate() method in the MainActivity when the onRunTask fires. Looking at the sample code, I am not 100% sure what I need of it, to do just this. – Peter May 18 '17 at 01:15

0 Answers0