Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better way to get Context?

According to this answer or the android's documentation there is several ways to get the Context in an app and pass it to an other class/method/whateveruneed.

Let's say I'm in the Foo Activity and in need to pass the context to Bar's constructor.

Bar bar  = new Bar(Foo.this);
Bar bar2 = new Bar(this); //same as first i guess
Bar bar3 = new Bar(getApplicationContext());
Bar bar4 = new Bar(getBaseContext());
Bar bar5 = new Bar(MyApp.getContext); // get context statically 

Taking into account of memory leaks, speed , general performance , what will be the better way between all those possibilities ?

like image 358
grunk Avatar asked Dec 14 '11 08:12

grunk


People also ask

How do you get context from anywhere?

Application Context : We can access it using getApplicationContext(). It returns the context for the entire application (the process inside which all activity is running). If somewhere in the activity we need a context which is tied to the whole application lifecycle and not just the activity.

How do you get the context of an application class?

Application Context This Context is tied to the Lifecycle of an Application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext().

How do you find the current context?

Kubectl current-context command shows the current context of kubectl. When you enter the 'kubectl config current-context' in the virtual machine environment, the following output will be displayed. The 'kubectl config use-context cluster-name' command is used to set the default context to the given cluster name.

What is context how is it used?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).


2 Answers

You should check out this question - which basicly covers the same as yours.

Also the Developer Docs on Avoiding memory leaks gives you a decent explanation of some situtations in which various of the methods are reasonable to use.

like image 110
kaspermoerch Avatar answered Sep 17 '22 19:09

kaspermoerch


I think that this post will provide you enough information. Look at the first response.

Difference between Activity Context and Application Context

like image 38
Bram Avatar answered Sep 18 '22 19:09

Bram