【android】关于getBaseContext();this等-----项目中遇到的问题

来源:互联网 发布:cc网络验证模块源码 编辑:程序博客网 时间:2024/04/19 16:29

      项目中要添加收藏功能,操作其实并不难:长按视频后弹出对话框,选择是否收藏,若选择是,则把视频的信息存入数据库中。在“我的收藏”页面中用listview载入数据库中的收藏的视频信息。

     完成这个功能期间,写了如下代码

<span style="font-size:18px;">PpVodItem selectedlikes=(PpVodItem)view.getTag();  OperateDAO newdao =new OperateDAO(getBaseContext());newdao.insertVodIntoPlayLikes(selectedlikes);</span>
    之前在getBaseContext()的位置是用this代替,eclipse始终报错,使用getBaseContext()却能正常进行,困扰我的问题用getBaseContext()轻易解决了。其实获得context的方法至少有三种:

Context = this; 
Context = getParent(); 
Context = getBaseContext(); 
Context = getParent(); 


三种方法的异同整理如下:


1.getApplicationContext ()方法在应用程序要被摧毁时,返回整个应用程序生命周期的应用上下文,生命周期是整个应用。


2.this应用上下文返回activity的当前上下文,属于activity。当它被摧毁时,activity也被摧毁。


3.getBaseContext()是 ContextWrapper中的方法,返回由构造函数指定或setBaseContext()设置的上下文。


4.getParent():若是子类,则返回子activity的上下文


getApplicationContext() Application context is associated with the Applicaition and will always be the same
throughout the life cycle.


getBasecontext() should not be used just use Context instead of it which is associated with the activity and could
possible be destroyed when the activity is destroyed.


getApplication() is available to Activity and Services only. Although in current Android Activity and Service
implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that


this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never callgetApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).


getParent() returns object of the activity if the current view is a child..In other words returns the activity object hosting the child view when called within the child.


0 0
原创粉丝点击