Use of Context to start another Activity - android

To start an Activity you need an Intent, like:
Intent i = new Intent(context, class)
So to fill in the context parameter, a couple of options are available:
Use MyActivity.this or just this
Use getApplicationContext()
Use getBaseContext()
And I'm sure there are one or two more options.
These options all appear in some sort of tutorial, one uses the first, the next uses the third option.
So which one should I use? Does it even matter? Is it different for different cases?

Yes its different for different cases,
It depends on the scope. Suppose if you are creating a method in a global class that extends Application to create a Toast that is used in every class of your Application you can use getApplicationContext() to create it.
If you want to create a view that is restricted to that particular Activity you can use Activity.this
Also if you want to create an AlertDialog in some inner class say AsyncTask, then you have to use Activity.this, because the AlertDialog is to be linked to Activity itself.
Also don't use getBaseContext() just use the Context that you are having. For getting further information for the same you can see this Answer.
So, the answer to the real question is better to use Activity.this to start a new Activity.
Intent intent = new Intent(Current_Activity.this, Calling.class);
startActivity(intent);

They are different for sure. These are different contexts, and should be used with the least possible scope(context).
For example if we can use Activity's Context instead of ApplicationContext, one should use the activity context, same applies to application context, and base context.

You do it like this....
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);

Related

Android Context used in classes other than Activity

In my Mainactivity:
LoginUser.loginUser(username.getText().toString(),password.getText().toString(), getApplication());
So in my LoginUser class,
I want to start a dialog box like this:
new AlertDialog.Builder(context).set.....
but failed,
get fault info like this:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Also I would like to use like
Intent intent = new Intent(context, ABC.class)
context.startActivity(intent);
Also failed. And get fault info like this:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I am so confused about all of these, can anyone help me? Thank you very much!
I'm not fully sure of what you're up to, but for the first problem, it looks like you're trying to use a non-activity context to show a dialog.
TL;DR, you cannot an AlertDialog with an application context, it requires an Activity.
Consider something like:
new AlertDialog.Builder(<activity>)
The second problem is also similar, you can start an activity with an application context, but you need to start it as a new task. To do that, you need to add a flag. (Although, this is not considered to be good practice)
Intent intent = new Intent(context, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Check here for more about what you can and cannot do with various types of contexts in Android.
Try this.
LoginUser.loginUser(username.getText().toString(),password.getText().toString(), Mainactivity.this);
replace getApllicationcontext() to your Activity.
new AlertDialog.Builder(<activity>)
You can use this as well
LoginUser.loginUser(username.getText().toString(),password.getText().toString(), this);
LoginUser.java
public void loginUser(Context context){
}

Android - Context argument in PendingIntent.getActivity

When creating a pending intent using the method PendingIntent.getActivity(), the first argument is (according to the android docs)
The Context in which this PendingIntent should start the activity.
When im lanuching a new instance of an activity in my application, i can pass getApplicationContext(). But if i want to launch an instance of another application's activity, what should be the context argument ?
This context is needed for startActivity(), so just pass what you did so far and it shall make no difference that the activiy you want to launch is in other package.
Just this context is OK. It is similar as you launch the activity by getApplicationContext().startActivity(intent) in your app.
You can use any Context you like to fire an Intent to another Application - Whether that be a Service, an Activity or a Context from getApplicationContext() or passed to you in a Receiver.

android - how to switch screens with an intent if the original class is not an Activity?

Usually if I want to switch screens, I do something like this:
Intent myIntent = new Intent(CurrActivity.this, NextActivity.class);
CurrActivity.this.startActivity(myIntent);
but I am in a situation where I would like to do this from a regular class. Actually it is an abstract class. It is named PurchaseObserver and its part of the Android billing setup.
Is it possible to do a change of screens from this class? Something similar to the intent code I posted above?
Thanks!
When you instantiate the class, pass a Context in the constructor and use that to start an Activity using startActivity(Intent)

difference and when to use getApplication(), getApplicationContext(), getBaseContext() and someClass.this

I'm new to android and I'm trying to understand the difference between getApplication(), getApplicationContext(), getBaseContext(), getContext() and someClass.this and especially when to use the these methods in the following code lines:
When I launch a toast what is the difference between these and in which cases to I use them?
Toast.makeText(LoginActivity.this, "LogIn successful", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplication(), "LogIn successful", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "LogIn successful", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "LogIn successful", Toast.LENGTH_SHORT).show();
same with intents:
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
Intent intent = new Intent(MenuPagina., LoginActivity.class);
Intent intent = new Intent(getBaseContext(), LoginActivity.class);
Intent intent = new Intent(getApplication(), LoginActivity.class);
Toast and Intent, both requires reference to context. And getApplication, getApplicationContext, LoginActivity.this and getBaseContext, they all offer reference to the context.
Now the thing confuses is the declaration of different contexts and their specific-usage. To make things simple, you should count two types of context available in the Android framework.
Application Context
Activity Context
Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window.
Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy() is raised. If you want to launch a new activity, you must need to use activity's context in its Intent so that the new launching activity is connected to the current activity (in terms of activity stack). However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
Now referring to your cases:
LoginActivity.this though its referring to your own class which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context.
getApplication() though its referring to Application object but the Application class extends Context class, so it can be used to offer application context.
getApplicationContext() offers application context.
getBaseContext() offers activity context.
Tips: Whenever you need to manipulate Views then go for
Activity-Context, else Application-Context would be enough.
The answer by Waqas is very clear and complete, however I'd like to further clarify the difference between using this vs. getBaseContext(), or getApplication() vs. getApplicationContext(). Both Activity and Application extend not Context itself, but ContextWrapper, which is a
"Proxying implementation of Context that simply delegates all of its calls to another Context".
That "real" context is what you get by using getBaseContext().
So although this (for Activity) and getBaseContext() both give the activity context, they
(a) do not refer to the same object (this != getBaseContext()) and
(b) calling context through this is slightly less efficient, as the calls go through an extra level of indirection. I doubt it makes any practical difference, though.
The same logic applies to getApplication() vs. getApplicationContext().
LoginActivity.this
the above line is an Activity which is obeveously a Context.. this is used when you create some AlertDialogs... At some places its compulsory that you use Activity Context...
getApplication()
Same here the make text method needs Context and Application itself implements Context
getApplicationContext()
this is most preferred way since this Context lives untill Application shuts down.
getBaseContext()
this Context is available to widgets and Views..
But All of them gives a Context object and nothing else..
Class.this used if your class extends Activity
getapplication() used refer application and application extends application context
getbasecontext()refer your activity context
context refer to your activity life cycle context
applicationcontext refer to your app life cycle

Use of Context in Explicit Intents

What is the difference between starting ActivityB from ActivityA using
1. startActivity(this, ActivityB.class);
versus
2. startActivity(getApplicationContext(), ActivityB.class);
I typically see 1. used more often in examples, but I haven't come across a reason for why this is the case.
Reference to Activity as a Context (this) might become obsolete if your Activity goes through configuration changes, like rotation, and is destroyed and created again. Context recieved by getApplicationContext(), however, persists through lifetime of the process.
However, It seems to me it only is an issue when you bind Activity to Service or other similar scenario, so it's safe to use this when you use it in intent to start another Activity.
There is no difference. According source code of Intent and ComponentName - only thing, that used form context - is getting package name by context.getPackageName(). Package name is the same for Activity.this and Activity.getApplicationContext(), so there is no difference.
I assume you are actually asking about the difference between
startActivity(new Intent(this, ActivityB.class));
and
startActivity(new Intent(getApplicationContext(), ActivityB.class));
There is no difference. Android needs the ComponentName (package name and class). The context is used to determine the package name.

Categories

Resources