Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

java - dealing with application context

I'm new to android and java.

I'm rearranging some of the classes in my app into separate class files. I had a onLocationListener class in my main activity class file. I moved the class to a separate java class file. Then, however the following code will not compile . . .

public void onProviderDisabled(String provider)
{
     Toast.makeText( getApplicationContext(),
     "Gps Disabled",
     Toast.LENGTH_SHORT ).show();
}

The getApplicationContext won't compile when this code is in a separate file. I tried this. and mainactivityname. but nothing seems to work. So I suppose this problem can be formed into a the following question:

How do you state the application context from code that exists in separate java class files outside the main activity file? thanks, Gary

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getApplicationContext() is a method of class Context, so you can only call it from a class or object that in some way extends Context. You factored your code out of Activity, which is such a class. Your solution, then, is for the Context class that contains your new class or object to pass its context in so that your new class can use it.

Your code inside your main Activity would look something like this:

MyOwnClass ownObject = new MyOwnClass();
// you have to implement setApplicationContext
ownObject.setApplicationContext( this.getApplicationContext() );

It's probably a good idea to get the application context right away, since it'll be stable for the lifetime of your app, unlike the Activity context which could go away on something as simple as an orientation change.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...