Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Application.onCreate(Bundle) be called before BroadcastReceiver.onReceive(..)?

Tags:

android

Just wanted to verify that Application.onCreate() is guaranteed to be called prior to BroadcastReceiver.onReceive() ? Let say you are waiting for BOOT broadcast or SMS broadcast, can you be sure that Application.onCreate() has already been called once before you reach BroadcastReceiver.onReceive()? Thanks

like image 721
MuayThai Avatar asked Oct 12 '15 10:10

MuayThai


3 Answers

Old question, however I can provide an updated answer and actual test results.

Originally I assumed so and set my application onCreate() to save app context first, like so:

@Override
public void onCreate()
{
    myapp.app_context = this;

    super.onCreate();

Now I got a receiver declared so:

    <receiver android:name=".myreceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
        </intent-filter>
    </receiver>

And in on receive:

@Override
public void onReceive(Context context, Intent intent)
{
    ctx = myapp.app_context;

Got a stack trace showing ctx (myapp.app_context) is NULL! Got 1 on an Android 6 Galaxy J7 device and 1 on an Android 9 Xperia XZ1.

like image 97
3c71 Avatar answered Oct 16 '22 13:10

3c71


The docs tell us the following:

public void onCreate ()

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

Found here: http://developer.android.com/reference/android/app/Application.html

like image 23
FiMi Avatar answered Oct 16 '22 14:10

FiMi


public void onReceive(Context context, Intent intent) If you register a static receiver, the context is the app otherwise it is the context where you call registerReceiver with

like image 5
Neil Avatar answered Oct 16 '22 14:10

Neil