0

I'm trying to launch an activity using application's context something like this,

This works

public class MyApplication extends Application {

    public static Context mContext = null;

    public MyApplication() {
        mContext = this;
    }
    public static void launchActivity() {
        Log.i(TAG, "Going to start main activity");
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(mContext.getPackageName(), MainActivity.class.getName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
        Log.i(TAG, "Successfully started the activity");
    }
}

This din't work

public class MyApplication extends Application {

    public MyApplication() {
        //Do nothing
    }
    public void launchActivity() {
        Log.i(TAG, "Going to start main activity");
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), MainActivity.class.getName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(intent);
        Log.i(TAG, "Successfully started the activity");
    }
}

I'm invoking this method launchActivity from my broadcast receiver which looks something similar to this,

public class MyReceiver extends BroadcastReceiver {

    public static final String TAG = "xyz";

    @Override
    public void onReceive(Context context, Intent intent) {
        MyApplication myApplication = new MyApplication();
        myApplication.upateUIModeValueViaBroadcast();
    }
}

I'm not understanding why getApplicationContext() returns me null when the application instance is new.

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • 2
    **NEVER** create an instance of an `Application` (or `Activity`, or `Service`) yourself. Only the framework can create those objects and properly wire them into the system. Also note that what you appear to be doing (launching an activity from the background) is banned on Android 10+ in most cases. – CommonsWare Nov 01 '19 at 11:37
  • @CommonsWare : Please suggest me some article to read more about why the application instance should not be created on my own - asking to understand more about what would happen internally.. – Tom Taylor Nov 01 '19 at 12:10

0 Answers0