Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an Intent if context is not Activity Context but Application Context

I'm trying to start an activity from a class that extends BroadcastReceiver.

public void onReceive(Context context, Intent intent) { 

the problem is that parameter context is the Application context and not an Activity context.

Is there a way start an intent using the Application context?

like image 240
MataMix Avatar asked Feb 11 '12 02:02

MataMix


People also ask

Can I start activity with application context?

In order to call startActivity with application context, include the flag FLAG_ACTIVITY_NEW_TASK. Also think about changing the name from context to appContext so it is clear which context you expect.

Can application context be passed using intent to another activity?

There is no way to pass the context to the target activity using Intent.

What is the difference between activity context and application context?

Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity.


1 Answers

Here is sample code how to call another activity using context, set flag as per your requirement:

public void onReceive(Context context, Intent intent) {           Intent intent = new Intent();        intent.setClass(context, xxx.class);      intent.setAction(xxx.class.getName());      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);      context.startActivity(intent);   } 
like image 182
SBJ Avatar answered Oct 04 '22 12:10

SBJ