处理应用程序上下文 [英] dealing with application context

查看:122
本文介绍了处理应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和Java。

I'm new to android and java.

我重新安排一些类在我的应用程序到单独的类文件。我的主要活动类文件有一个onLocationListener类。我搬到类到一个单独的Java类文件。然后,但以下code将无法编译。 。

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();
}

在此code是在一个单独的文件中的getApplicationContext将无法编译。我试过的这一点。的和的 mainactivityname。的,但似乎没有任何工作。所以我想这个问题就可以形成一个以下问题:

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:

你如何从状态code存在于不同的Java类文件的主要活动文件之外的应用程序上下文?
谢谢,加里

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

推荐答案

<一个href=\"http://developer.android.com/reference/android/content/Context.html#getApplicationContext%28%29\"相对=nofollow> getApplicationContext()是类语境的方法,所以你只能从一个类调用或对象以某种方式延长上下文。你的因素code OUT 活动,这是这样的类。您的解决方案,那么,是包含新类或对象通过它的上下文中,使自己的新类可以使用它的上下文类。

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.

您的主要活动内,您的code会是这个样子:

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.

这篇关于处理应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆