`

getApplicationContext()与this,getBaseContext()

阅读更多
转自:http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context


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.
分享到:
评论
1 楼 xukaiyin 2015-06-25  
全英文

相关推荐

    Android Context与GetApplicationContext的区别及使用1

    【Android Context 与 GetApplicationContext 的区别及使用】 在Android开发中,Context是一个至关重要的概念,它扮演着应用程序组件与系统服务交互的关键角色。Context可以理解为应用运行时的上下文环境,提供了对...

    android中用getApplicationContext()会不会避免某些内存泄漏问题?

    RT,在android开发中,如果在使用context的地方全部用getApplicationContext()会不会避免某些内存泄漏问题? 首先,Activity的Context和Application的Context肯定不是一个东西,一个是当前活动的 Context,它的生命...

    libstreaming-master.zip

    .setContext(getApplicationContext()) .setVideoEncoder(SessionBuilder.VIDEO_H264) .setVideoQuality(new VideoQuality(1280, 720)); this.startService(new Intent(this,RtspServer.class));

    安卓Crash日志收集器.zip

    在Application的onCreate()中进行初始化{ CrashLogUtil.init(getBaseContext(), getApplicationContext().getExternalFilesDir("crash_log").getPath());}通过File logDir = new File(CrashLogUtil.getInstance()....

    Spring获取ApplicationContext对象工具类的实现方法

    然后,通过getApplicationContext方法,可以返回这个已经加载好的ApplicationContext实例。 使用这个工具类非常简单。例如,如果你需要获取一个名为"userService"的Bean实例,可以这样做: ```java public static ...

    安卓总结的文档

    安卓基本语句有public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here.... myIntent=new Intent(getApplicationContext(), FrmMain.class); } //2监听器

    permissions.jar

    PermissionHelper.requestPermission(this, new RequestPermissionListener() { @Override public void onSuccess() { Toast.makeText(getApplicationContext(),"权限成功获取",Toast.LENGTH_SHORT).show(); } ...

    permissions-x.jar

    PermissionHelper.requestPermission(this, new RequestPermissionListener() { @Override public void onSuccess() { Toast.makeText(getApplicationContext(),"权限成功获取",Toast.LENGTH_SHORT).show(); } ...

    Android 文件读写源码

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

    Toast显示问题

    为避免这种情况,尽量使用`getApplicationContext()`或`getBaseContext()`创建`Toast`,而不是使用`Activity`的`this`。如果在`Activity`中使用`this`,确保在`Activity`的`onDestroy()`方法中调用`toast.cancel()`...

    android-exercise

    getBaseContext() 或这个(在活动课程中) 上下文使用示例: 创建新对象:创建新视图,适配器,侦听器 TextView tv = new TextView (getContext()); ListAdapter adapter = new SimpleCursorAdapter ...

    生活轨迹Android端

    Toast.makeText(YLC_APPLICATION.getInstance().getApplicationContext(), "您的网络出错啦!", Toast.LENGTH_LONG).show(); }else if (isError == MKEvent.ERROR_NETWORK_DATA) { Toast.makeText(YLC_...

    Android代码-CameraModule

    ManagerInitializer.i.init(getApplicationContext()); } } Then call CameraActivity to use camera: Intent intent = new Intent(this, CameraActivity.class); intent.putExtra(CameraActivity.PAT

    Android输入手机号发送短信示例.rar

      PendingIntent sendPI = PendingIntent.getBroadcast(getApplicationContext(), 0, intentSend, 0);   smsManager.sendTextMessage(strNumber, null, strBody, sendPI, null);//发送短信   send.setEnabled...

    Android Context使用例子.

    一般通过`this`或`getContext()`获取,适合执行与当前Activity相关的操作。 三、`Context`的常用方法 1. **获取资源**:如`getString()`, `getColor()`, `getDrawable()`等,用于获取字符串、颜色、图片等资源。 2....

    日历

    根据提供的信息来看,这段代码似乎涉及到了一个应用中与日历功能不相关的部分,而是在实现一个具有地理位置选择功能的应用程序。尽管如此,我们依然可以从这段代码中提取出一些关于日历应用程序可能涉及的技术点。 ...

    放微信图片编辑器aar包

    第二个参数是否保存编辑后的照片与你指定的路径.默认为false. 2.实现ImageEditeStateListener接口 fragment.setImageEditeStateListener(new ImageEditeStateListener() { @Override public void ...

    Zebra斑马PDA对接Android

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

    AppInfoBean.zip

    在Android开发中,`AppInfoBean.zip`这个文件名暗示我们可能在处理一个与应用程序信息相关的Java类。从标签"android"我们可以推断,这涉及到Android应用开发中的一个特定组件或者数据模型。在这个场景下,`...

Global site tag (gtag.js) - Google Analytics