`

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

    1、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));

    安卓总结的文档

    安卓基本语句有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{ ...

    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...

    放微信图片编辑器aar包

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

    AssetsCopier:因为我们在开发android应用程序时无法在C ++(JNI)代码中使用文件的绝对路径。 因此,我们将资产文件复制到SdCard

    我们可以使用AssetsCopier的静态函数: 公共静态无效copyAllAssets(上下文上下文,字符串目标) 基本用法如下: AssetsCopier.copyAllAssets(this.getApplicationContext(),this.getExternalFilesDir(null)....

    android-lotterywheel-这是一个抽奖转盘.zip

    这是一个抽奖转盘项目地址... lotterywheel.setOnSelectListener(new SelectListener() { @Override public void onSelect(String str) { Toast.makeText(getApplicationContext(), str, 0).show(); }显示对效果如下:

    Android webview 内存泄露的解决方法

    最近在activity嵌套webview显示大量图文发现APP内存一直在涨,没法释放内存,查了很多资料,大概是webview的一个BUG,引用了activity导致内存泄漏,所以就尝试传递getApplicationContext。 1.避免在xml直接写webview...

    word源码java-Hello-Fan:高级软件实作,繁体字学习软件,你好繁!

    一般而言,如果context不需要ui相关的操作,就用getApplicationContext()。如果对象存活时间可能比activity长,考虑使用getApplicationContext()。其他情况,确保activity销毁前,取消引用activity,用this就好了。 ...

    Androiddiffpatch方案android-diffpatch.zip

    bsDiffPatch.init(getApplicationContext());  //diff bsDiffPatch.diff(oldFilePath, newFilePath, diffFilePath); //patch bsDiffPatch.patch(oldFilePath, diffFilePath, gennewFilePath);...

    WifiUtils:轻松连接到WiFi网络

    WiFi Utils是一个库,提供了一组方便的方法来管理WiFi状态,WiFi扫描以及与热点的WiFi连接。 如果您曾经使用过WifiManager ,则应该知道进行简单的wifi网络扫描是多么痛苦,或者以编程方式连接到热点甚至更糟。 这...

    崩溃日志上传框架LogReport.zip

     .setLogDir(getApplicationContext(), "sdcard/" this.getString(this.getApplicationInfo().labelRes) "/")//定义路径为:sdcard/[app name]/  .setWifiOnly(true)//设置只在Wifi状态下上传,设置为false为...

Global site tag (gtag.js) - Google Analytics