23

As we know content provider loads on application run. But I want to make some operations before content provider will launch. How do I catch this operation? Before content provider's onCreate method would be called

pleerock
  • 18,322
  • 16
  • 103
  • 128

2 Answers2

34

I think Ive found solution. Ive created my custom application class and overridden attachBaseContext method

<application android:name=".ApplicationController" ...>

public class ApplicationController extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        // some of your own operations before content provider will launch
    }
}
pleerock
  • 18,322
  • 16
  • 103
  • 128
  • 3
    That may work at the moment, but I do not know if it will be reliable across versions. – CommonsWare Mar 26 '12 at 16:42
  • 1
    Its survived across 17 apis )) Maybe in the feature google will provide us any apis for this operation, but for now it works. Thank you for reply! – pleerock Mar 26 '12 at 17:03
  • 1
    This solution works, however it's not fully functional. For instance, the `Context.getMainLooper()` method returns `null` when called before `Application.onCreate()`. – Michael Jul 27 '12 at 10:46
  • 2
    Be carefully: in this method `getApplicationContext()` will also return `null`, because the `Application.onCreate()` is not called yet. – codezjx Mar 17 '17 at 11:00
4

My solution requires use of the call(Uri, String, String, Bundle) API (so, it's not fully backward-compatible). But I have the stuff that I want the ContentProvider to prepare before it is used in my override of that call method. Then I do getContentResolver().call(BASE_URI, METHOD, null, Bundle.EMPTY) in my Application.onCreate(). Essentially, it defers that stuff until after my Application is being created, which is what we expected the ContentProvider's onCreate to be doing naturally.

Dandre Allison
  • 5,975
  • 5
  • 42
  • 56