-1

I have a service running in an android app. When the user goes to Settings -> App Manager and clears the app data, it clears all the databases, files, sharedpreferences, contentproviders of the app. Also, kills the services running. I am looking to auto-start the service after the 'Clear Data' event. Or otherwise, listen to the 'Clear Data' event.

Android provides broadcast intent ACTION_PACKAGE_DATA_CLEARED. But I get this broadcast when any other app's data is cleared.

Xenolion
  • 12,035
  • 7
  • 33
  • 48
Puneet Chugh
  • 93
  • 10
  • Why a downvote ? This has been one of the gray topics in android that I don't find mention anywhere – Puneet Chugh Apr 12 '18 at 20:58
  • Can you answer why 'downvote' ? Its a genuine question with full information – Puneet Chugh Apr 12 '18 at 21:00
  • 1
    "Or otherwise, listen to the 'Clear Data' event" -- I am fairly certain that this is not offered. Are you using `START_STICKY` or `START_REDELIVER_INTENT` as the return value from your `onStartCommand()` method in your service? – CommonsWare Apr 12 '18 at 21:07
  • I am using START_STICKY – Puneet Chugh Apr 12 '18 at 21:12
  • When your data is cleared, it is as if the user has downloaded your app that time...Then can you start a service when your app has just been downloaded?? – Xenolion Apr 12 '18 at 21:13
  • Using ACTION_PACKAGE_DATA_CLEARED, you can listen to Clear Data event. For example, I cleared the app data of Android Calendar app, and I received this broadcast, but not when I clear my own app's data – Puneet Chugh Apr 12 '18 at 21:13
  • Hmmm... I would have thought that would have been sufficient to have your service be restarted sometime after the data was cleared. With the "Force Stop" button, your app won't run again until the user does something to start it (e.g., runs your launcher activity). You could see if Android is stopping your process gracefully, calling `onDestroy()` on your service. If the `onDestroy()` is unexpected (i.e., you aren't stopping the service yourself), you can try using `AlarmManager` to wake you up in a minute, but I have no idea how well this will work. – CommonsWare Apr 12 '18 at 21:16
  • IMHO, "Clear Data" is a fairly fringe event, and one where the user should not be expecting your app to start up again. – CommonsWare Apr 12 '18 at 21:16

1 Answers1

0
public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      String package = intent.getPackage();
      if(package!=null && package.equals("com.your.app.package")){
         // then do something you want to do. maybe start your service again?
          }
   }
}

You can use the intent from onReceive to check its package. if it belongs to your app then only do your thing. else ignore the broadcast

Deepak kaku
  • 1,218
  • 9
  • 15