0

I'm developing an app that needs to find a file on device. This process runs for 5 minutes trying to find the file.

My app starts after a BroadcastReceiver for boot_completed. After file search a service starts.

Below is the code for finding the file in until 5 minutes. This process repeats every 1 minute.

boolean found = false;
int tam = 0;
While(!found)
{

  found = find_file(); //call  the method to find the file. 

  Handler handler = new Handler();
  handler.postDelayed(new Runnable() {
  @Override
      public void run() {        
      }
  }, 60000); 
  tam++

  if(tam==5){
  break;
  }

}

Questions:

  1. Is there a better way to do this ?
  2. Could the operating system kill my app to save memory, causing the service to never be executed?
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kirei
  • 1
  • 2

2 Answers2

0

Android can kill an unbound background service in an app that isn't foreground at any time. In fact it would be the top of the list for what to kill. So no, this won't work reliably. You could make it more reliable via a Foreground service. My real question is why are you taking 5 minutes to find a file? Most likely you're doing something wrong there.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

You can try using a foreground service. This will give high priority to service process and android system is very less likely to kill the service.

https://developer.android.com/guide/components/services

You can refer to

Android - implementing startForeground for a service?

for understanding how to start your service as a foreground service.

Eldhose M Babu
  • 14,382
  • 8
  • 39
  • 44