`
ylzyd12345
  • 浏览: 121170 次
  • 性别: Icon_minigender_1
  • 来自: 江苏
博客专栏
713488f4-d0a9-3f35-997f-199fb0cb3563
玩懂Log,打开Andro...
浏览量:10509
社区版块
存档分类
最新评论

getApplicationContext() 与 Activity.this

阅读更多
 写道
In various bits of Android code I've seen:

public class MyActivity extends Activity {
public void method() {
mContext = this; // since Activity extends Context
mContext = getApplicationContext();
mContext = getBaseContext();
}
}
However I can't find any decent explanation of which is preferable, and under what circumstances which should be used.

Pointers to documentation on this, and guidance about what might break if the wrong one is chosen, would be much appreciated.



I agree that documentation is sparse when it comes to Contexts in Android, but you can piece together a few facts from various sources.

This blog post on the official Google Android developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:

In a regular Android application, you usually have two kinds of Context, Activity and Application.

Reading the article a little bit further tells about the difference between to the two and why you might want to consider using the application Context (Activity.getApplicaitonContext()) rather than using the Activity context ("this"). Basically the Application context is associated with the Applicaiton and will always be the same throughout the life cycle of you app, where as the Activity context is associated with the activity and could possible be destroyed many times as the activity is destroyed during screen orientation changes and such.

I couldn't find really anything about when to use getBaseContext() other than a for a one liner from Dianne Hackborn, one of the Google engineers working on the Android SDK:

Don't use getBaseContext(), just use the Context you have.

That was from a post on the android-developers newsgroup, you may want to consider asking your question there as well because a handful of the people working on Android actual monitor that newsgroup and answer questions.

So overall it seems preferable to use the global application context when possible.


I got bad window token errors when using application context to Progress Dialog. So i used activity context instead.

 最关键的地方---- 写道

Basically the Application context is associated with the Applicaiton and will always be the same throughout the life cycle of you app, where as the Activity context is associated with the activity and could possible be destroyed many times as the activity is destroyed during screen orientation changes and such.

   以及最后一句,因为我就是使用官方的例子出现了错误:写道

I got bad window token errors when using application context to Progress Dialog. So i used activity context instead.

 -------------------------分割线:上面 的是从网上搜得解释;下面是我遇到的问题--------------------------

 

 

 写道
官方网站:http://developer.android.com/guide/topics/ui/dialogs.html

Creating a Custom Dialog
第二步:Set the above layout as the dialog's content view and define the content for the ImageView and TextView elements:

按照这个代码来写,会报错误;

如果把上下文 Context mContext = getApplicationContext();
---改为--- Context mContext = Activity类名.this 就正确。
分享到:
评论
1 楼 twlkyao 2013-12-28  
这个貌似是StackOverflow上的http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context

相关推荐

    Android Context与GetApplicationContext的区别及使用1

    而`getApplicationContext()`返回的是Application的Context,这是一个全局的、与应用程序生命周期相同的Context,不受任何特定Activity或Service的影响。 - **Activity Context**:主要用于与用户界面交互,如启动...

    图片选择器

    Intent intent=new Intent(Main2Activity.this,CCwantPhotoBrowserActivity.class); intent.putExtra("CCwantPhotoList",(Serializable) mData); intent.putExtra("CCwantPhotoPosition",(Serializable)position)...

    安卓期末复习资料整理全.pdf

    - **ContentResolver**:用于与ContentProvider交互,通过getApplicationContext().getContentResolver()获取ContentResolver对象,然后调用其query(), insert(), update(), delete()方法来操作ContentProvider中的...

    Android 文件读写源码

    Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new ButtonClickListener()); } private final class ButtonClickListener implements View.OnClickListener{ ...

    谈谈Android里的Context的使用

    大家好,今天给大家分享一下Android... aContext = getApplicationContext(); } /**获取Context. * @return */ public static Context getContext(){ return aContext; } } 第5步:运行上述工程效果如下:

    Android-AppIconNameChanger以编程方式更改Android应用启动器图标和App名称

    Activity activity = this; // 当前Activity ComponentName componentName = new ComponentName(activity, activity.getClass()); ActivityInfo activityInfo = activity.getPackageManager().getActivityInfo...

    安卓总结的文档

    etUserName=(EditText) this.findViewById(R.id.etUserName); etPassword=(EditText) this.findViewById(R.id.etPassword); btnLogin=(Button) this.findViewById(R.id.btnLogin); btnReset=(Button) this....

    Java基础类.pdf

    - 使用`getApplicationContext()`可以获取应用级别的Context,而使用`this`或`getActivity()`可以获得当前Activity的上下文。 3. Activity的生命周期和管理: Activity是Android应用中的主要界面单元,它提供了...

    android 屏幕截图功能

    1. **启用绘图缓存**:首先需要启用WebView或Activity视图的绘图缓存。 2. **获取Bitmap**:通过调用`getDrawingCache()`方法获取视图的Bitmap。 3. **压缩并保存**:将Bitmap压缩成JPEG格式,并保存至指定路径。 #...

    页面跳转OnClickListener

    本篇将详细讲解页面跳转的五种方法,以及与之相关的Android基础知识。 1. 实现接口的方式: 这是最基础的实现方式,创建一个新的类去实现View.OnClickListener接口,然后在onClick()方法中编写点击事件的逻辑。...

    AppInfoBean.zip

    public void setFirstInstallTime(Date firstInstallTime) { this.firstInstallTime = firstInstallTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date ...

    android微信分享

    getApplicationContext().startActivity(intent); } } ``` 实现分享功能,需要调用微信SDK提供的`WXWebpageObject`、`WXImageObject`或`WXTextObject`类来构造分享内容。例如,分享图片和文字可以这样实现: ```...

    Android动态更换图标

    PackageManager pm = getApplicationContext().getPackageManager(); PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_META_DATA); ``` 2. 创建一个新的ComponentInfo对象,设置新的图标...

    Android程序研发源码Android 调用系统相册和系统照相机功能雨实例源码.rar

    Uri photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); ``` 注意:为了安全访问文件,...

    android 百度地图 定位示例

    SDKInitializer.initialize(getApplicationContext()); //当前视图 setContentView(R.layout.activity_map_api_demo); //创建地图对象 init(); final Button btn_location = (Button) findViewById(R...

    利用Application 在2个不同的Activity传递数据

    public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` ...

    Safe Guarder安全陪护软件

    - **地图视图与控制器**:通过`MapView`和`MapController`管理地图显示与操作。 - **地理坐标点管理**:通过`GeoPoint`类处理地理位置数据。 #### 三、核心代码解析 ##### MainActivity.java ```java package ...

    快捷方式桌面+权限是否存在

    shortcutIntent.setComponent(new ComponentName(this, YourActivity.class)); shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式名称"); Parcelable icon = Intent.ShortcutIconResource....

    基于startActivityForResult方法处理两个Activity之间数据传递问题

    ActivityB.this.setResult(Changliang.requestCode, intent); ``` 最后,我们返回到 `MainActivity` 的 `onActivityResult` 方法。这个方法会在 `ActivityB` 结束并返回结果时被调用。我们通过请求码和结果代码来...

    Zebra斑马PDA对接Android

    在与Android系统的对接过程中,我们可以实现更高效的数据管理和业务流程自动化。 标题"Zebra斑马PDA对接Android"涉及到的关键知识点主要包括以下几个方面: 1. **硬件接口**:Zebra斑马PDA通常配备有多种接口,如...

Global site tag (gtag.js) - Google Analytics