0

I am creating an android app which needs a background service that fetches location and sends data to firebase every 20 seconds.The service has to start on button click and run continuously even when screen is turned off and should stop again on button click. At first , I tried using alarm Manager but it was not performing tasks at regular intervals. Next I tired using an Async Task and it was invoking a service which was performing task of sending data to firebase. But this approach, did not work on android 8+ versions. Then later on I used the similar approach but with JobIntent service and this approach worked well in android 7(appo) and even in android 8(lava) but in 8+ version(appo reno and mi) maybe due to custom OS , the service does not work if screen is turned off . I tried alternatives like workmanager but it did not work well in higher versions.

I created an activity named punch activity which has two buttons and code is as follows -

  1. This button uses an async activity which calls service every 20 seconds.
              @Override
              public void onClick(View v) {
                  if (punchedIn){
                      Toast.makeText(PunchActivity.this, "Already PunchedIn",
                              Toast.LENGTH_LONG).show();
                  }
                  else {
                                          timertask = new TimerTask() {
                                              @Override
                                              public void run() {
                                                  handler.post(new Runnable() {
                                                      public void run() {
                                                          Intent intent = new Intent(PunchActivity.this, BackgroundService.class);
                                                          //sendBroadcast(intent);
                                                          BackgroundService.enqueueWork(PunchActivity.this, intent);
  
                                                      }
                                                  });
                                              }
                                          };
                                          timer = new Timer();
                                          timer.schedule(timertask, 0, 20000);
                                      }
                                  }
  
                              }};
  1. This button stops the service

        @Override
        public void onClick(View v) {
            punchedIn = false;
            Toast.makeText(getApplicationContext(),"PUNCHED OUT",Toast.LENGTH_SHORT).show();
            Log.d("Message","Process "+timer.toString());
            if (timer != null) {
                Log.d("Message","Process is killed");
                timer.cancel();
                timer = null;
                wakeLock.release();
            }
        }
    });```
    
    

The code for JobIntentService is as below

public class BackgroundService extends JobIntentService implements com.google.android.gms.location.LocationListener {

    private static Context mContext;
    private FusedLocationProviderClient fusedLocationProviderClient;
    public static String latitude = "", longitude = "";
    public static void enqueueWork(Context context, Intent work) {
        mContext = context;
        enqueueWork(context, BackgroundService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        //This task does the task of fetching location and sending data to firebase
        YourTask();
    }

}```

I have made use of power manager in punch activity but it did not work fine. So please give some suggestions or even rectify my approach if you find any issue, based on my use case . Any small clue could be helpful.


Thanks,

Vrashab

1 Answers1

0

Just create a sub thread and request location in a loop like below:

private HandlerThread thread = new HandlerThread("location_thread");
private Handler locationHandler = new Handler(thread.getLoop())
private boolean sholdStop = false
private Runnable locationRunnable = new Runnable() {
        while(!sholdStop) {
            // location logic
            ...
            Thread.sleep(20000);
        }
    });
// start to location per 20 seconds
public void startLocation() {
    locationHandler.removeCallbacks(locationRunnable);
    sholdStop = false;
    locationHandler.post(locationRunnable);
}

public void stopLocation() {
    sholdStop = true;
    locationHandler.removeCallbacks(locationRunnable);
}

But if your app is killed by Android system, this code will be invalid. To solve this problem you might need some method to keep your app lives as long as possible when running background.

leimenghao
  • 226
  • 1
  • 10
  • Thanks leimenghao . But the code for fetching location and sending data to firebase is already in the function **YourTask()**. Just I need a way to call this function every 20 sec even in background and even after screen turn off. – Vrashab Kotian Jul 02 '20 at 12:48
  • Just put location locgic and `YourTask()` below the annotation of `// location logic`. There is no need to call `startLocation()` per 20 sec as `locationRunnable` does this in `while` loop. – leimenghao Jul 03 '20 at 01:56
  • Thanks . I want to also keep my app running even if screen is turned off . Do you have any suggestion for that? – Vrashab Kotian Jul 03 '20 at 06:15
  • Does the code not work when turning the screen off ? I think your app is still active when screen off, and the code still works. Did you test it ? – leimenghao Jul 03 '20 at 08:50
  • Yes it stops after some times after screen turn off depending on the mobile make. At most, it has worked upto 2 hrs – Vrashab Kotian Jul 07 '20 at 05:33
  • If you want to make an application that resides in the background, you can use a service and call `startLocation()` in this service.When the service is started, post an app notification in `Service.onCreate` that will be displayed in the notification bar to keep the app alive. Read [this post answer](https://stackoverflow.com/questions/54124631/how-to-keep-my-android-app-alive-in-background-for-24-7-continuous-sensor-data-c) – leimenghao Jul 07 '20 at 06:40