码迷,mamicode.com
首页 > Web开发 > 详细

webview 缓存

时间:2016-06-13 19:15:46      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

What is ‘Context‘ on Android?

Putting it simply:

As the name suggests, it‘s the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

Typical uses of context:

•Creating new objects: Creating new views, adapters, listeners:
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);


•Accessing standard common resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(*name*, *mode*);


•Accessing components implicitly: Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri, ...);

 

=====
Definition of Context::
•Context represents environment data
•It provides access to things such as databases

Simpler terms ::

•Consider Person-X is the CEO of a start-up software company.


•There is a lead architect present in the company, this lead architect does all the work in the company which involves such as database, UI etc.


•Now the CEO Hires a new Developer.


•It is the Architect who tells the responsibility of the newly hired person based on the skills of the new person that whether he will work on Database or UI etc.


Simpler terms ::

•It‘s like access of android activity to the app‘s resource.


•It‘s similar to when you visit a hotel, you want breakfast, lunch & dinner in the suitable timings, right?


•There are many other things you like during the time of stay. How do you get these things?


•You ask the room-service person to bring these things for you.


•Here the room-service person is the context considering you are the single activity and the hotel to be your app, finally the breakfast, lunch & dinner have to be the resources.

 

Things that involve context are:
1.Loading a resource.
2.Launching a new activity.
3.Creating views.
4.obtaining system service.


Context is the base class for Activity, Service, Application .... etc

Another way to describe this: Consider context as remote of a TV & channel‘s in the television are resources, services, using intents etc - - - Here remote acts as an access to get access to all the different resources into foreground.
•So, Remote has access to channels such as resources, services, using intents etc ....
•Likewise ..... Whoever has access to remote naturally has access to all the things such as resources, services, using intents etc


Different invoking methods by which you can get context
•getApplicationContext()
•getContext()
•getBaseContext()
•or this (when in the activity class)


Example:
TextView TV=new TextView(this);

this -> refers to the context of the current activity.

=========
The topic of Context in Android seems to be confusing too many. People just know that Context is needed quite often to do basic things in Android. People sometimes panic because they try to do perform some operation that requires the Context and they don’t know how to “get” the right Context. I’m going to try to demystify the idea of Context in Android. A full treatment of the issue is beyond the scope of this post, but I’ll try to give a general overview so that you have a sense of what Context is and how to use it. To understand what Context is, let’s take a look at the source code:

http://codesearch.google.com/codesearch#search&q=package:android.git.kernel.org+file:android/content/Context.java

What exactly is Context?

Well, the documentation itself provides a rather straightforward explanation: The Context class is an “Interface to global information about an application environment".

The Context class itself is declared as abstract class, whose implementation is provided by the Android OS. The documentation further provides that Context “…allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc".

You can understand very well, now, why the name is Context. It’s because it’s just that. The Context provides the link or hook, if you will, for an Activity, Service, or any other component, thereby linking it to the system, enabling access to the global application environment. In other words: the Context provides the answer to the components question of “where the hell am I in relation to app generally and how do I access/communicate with the rest of the app?” If this all seems a bit confusing, a quick look at the methods exposed by the Context class provides some further clues about its true nature.

Here’s a random sampling of those methods: 1. getAssets() 2. getResources() 3. getPackageManager() 4. getString() 5. getSharedPrefsFile()

What do all these methods have in common? They all enable whoever has access to the Context to be able to access application-wide resources.

Context, in other words, hooks the component that has a reference to it to the rest of application environment. The assets (think ’/assets’ folder in your project), for example, are available across the application, provided that an Activity, Service or whatever knows how to access those resources. Same goes for “getResources()” which allows to do things like “getResources().getColor()” which will hook you into the colors.xml resource (nevermind that aapt enables access to resources via java code, that’s a separate issue).

The upshot is that Context is what enables access to system resources and its what hooks components into the “greater app". Let’s look at the subclasses of Context, the classes that provide the implementation of the abstract Context class. The most obvious class is the Activity class. Activity inherits from ContextThemeWrapper, which inherits from ContextWrapper, which inherits from Context itself. Those classes are useful to look at to understand things at a deeper level, but for now it’s sufficient to know that ContextThemeWrapper and ContextWrapper are pretty much what they sound like. They implement the abstract elements of the Context class itself by “wrapping” a context (the actual context) and delegating those functions to that context. An example is helpful - in the ContextWrapper class, the abstract method “getAssets” from the Context class is implemented as follows:
@Override
public AssetManager getAssets() {
return mBase.getAssets();
}

mBase is simply a field set by the constructor to a specific context. So a context is wrapped and the ContextWrapper delegates its implementation of the getAssets method to that context. Let’s get back to examining the Activity class which ultimately inherits from Context to see how this all works.

You probably know what an Activity is, but to review - it’s basically ‘a single thing the user can do. It takes care of providing a window in which to place the UI that the user interacts with‘. Developers familiar with other APIs and even non-developers might think of it vernacularly as a “screen.” That’s technically inaccurate, but it doesn’t matter for our purposes. So how do Activity and Context interact and what exactly is going in their inheritance relationship?

Again, it’s helpful to look at specific examples. We all know how to launch Activities. Provided you have “the context” from which you are you are starting the Activity, you simply call startActivity(intent), where the Intent describes the context from which you are starting an Activity and the Activity you’d like to start. This is the familiar startActivity(this, SomeOtherActivity.class).

And what is “this”? “this” is your Activity because the Activity class inherits from Context. The full scoop is like this: When you call startActivity, ultimately the Activity class executes something like this:
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode);

Ok, so it utilizes the execStartActivity from the Instrumentation class (actually from an inner class in Instrumentation called ActivityResult).

At this point we are beginning to get a peek at the system internals.

This is where OS actually handles everything. So how does Instrumentation start the Activity exactly? Well, the param “this” in the execStartActivity method above is the your Activity, i.e. the Context, and the execStartActivity makes use of this context.

A 30,000 overview is this: the Instrumentation class keeps tracks of a list of Activities that it’s monitoring in order to do it’s work. This list is used to coordinate all of the activities and make sure everything runs smoothly in managing the flow of activities.

There are some operations which I haven’t fully looked into which coordinate thread and process issues. Ultimately, the ActivityResult uses a native operation - ActivityManagerNative.getDefault().startActivity() which uses the Context that you passed in when you called startActivity. The context you passed in is used to assist in “intent resolution” if needed. Intent resolution is the process by which the system can determine the target of the intent if it is not supplied. (Check out the guide here for more details).

And in order for Android to do this, it needs access to information that is supplied by Context. Specifically, the system needs to access to a ContentResolver so it can “determine the MIME type of the intent’s data". This whole bit about how startActivity makes use of context was a bit complicated and I don’t fully understand the internals myself. My main point was just to illustrate how application-wide resources need to be accessed in order to perform many of the operations that are essential to an app. Context is what provides access to these resources. A simpler example might be Views. We all know what you create a custom View by extending RelativeLayout or some other View class, you must provide a constructor that takes a Context as an argument. When you instantiate your custom View you pass in the context. Why? Because the View needs to be able to have access to themes, resources, and other View configuration details. View configuration is actually a great example. Each Context has various parameters (fields in Context’s implementations) that are set by the OS itself for things like the dimension or density of the display. It’s easy to see why this information is important for setting up Views, etc.

One final word: For some reason people new to Android (and even people not so new) seem to completely forget about object-oriented programming when it comes to Android. For some reason, people try to bend their Android development to pre-conceived paradigms or learned behaviors.

Android has it’s own paradigm and a certain pattern that is actually quite consistent if let go of your pre-conceived notions and simply read the documentation and dev guide. My real point, however, while “getting the right context” can sometimes be tricky, people unjustifiably panic because they run into a situation where they need the context and think they don’t have it. Once again, Java is an object-oriented language with an inheritance design.

You only “have” the context inside of your Activity because your activity itself inherits from Context. There’s no magic to it (except for the all the stuff the OS does by itself to set various parameters and to correctly “configure” your context). So, putting memory/performance issues aside (e.g. holding references to context when you don’t need to or doing it in a way that has negative consequences on memory, etc), Context is an object like any other and it can be passed around just like any POJO (Plain Old Java Object). Sometimes you might need to do clever things to retrieve that context, but any regular Java class that extends from nothing other than Object itself can be written in a way that has access to context; simply expose a public method that takes a context and then use it in that class as needed. This was not intended as an exhaustive treatment on Context or Android internals, but I hope it’s helpful in demystifying Context a little bit.

=========
有寫過android的人,對context一定不陌生
但是context的用法與時機卻不一定能搞的清楚
到底該用this,還是用ClassName.this,還是用getActivity(),還是用getApplicationContext()呢?


android学习—— context 和 getApplicationContext()
[一般问题] Android基础概念Context的作用
看到很多Android程序里面传Context对象,但不知道这个对象怎么理解,对应AP的实例还是什么其它?
difference between this, Class.this and getApplicationContext

 

============
今天在项目中发现一个BUG

在使用新浪微博账户登录应用时,webview会自动登录上次的微博帐号!(因为webview 记录了微博帐号和密码的cookies)

所以,需要清除SessionCookie:

CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().removeSessionCookie();

另外,清理cache和历史记录 的方法:

webView.clearCache(true);
webView.clearHistory();

===========
最近项目中遇到用webView显示内容的需求,接到任务后代码如下

// 更新加载进度条
wv_setmeal_detail.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
pb_webview.setProgress(progress);
if (progress == 100) {
pb_webview.setVisibility(View.GONE);
}
}
});

wv_setmeal_detail.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(self, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});

// 加载网页
wv_setmeal_detail.loadUrl(url);


嗯,没问题,显示的很好,但是测试时发现一个坑爹的问题,就是退出当前账号换其他账号登录时webview显示的内容还是之前账号的信息,额...怪了.想想肯定是缓存搞的鬼,好,接下来就是清除缓存.

 

网上各种google baidu,发现很多方法都不管用.做法一般如下

1.websettings设置不适用缓存

mCurrentWebView.clearCache(true);
mCurrentWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

其实不管用...

2.webview显示时会自动生成如下文件 data/data/<包名>/app_webview

然后就是循环遍历删除该文件下的内容

/**
* 清除WebView缓存
*/
public void clearWebViewCache() {


// WebView 缓存文件
File appCacheDir = new File(DATA_BASE_PATH + getPackageName() + APP_WEBVIEW_PATH);


if (appCacheDir.exists()) {
deleteFile(appCacheDir);
}
}


/**
* 递归删除 文件/文件夹
*
* @param file
*/
public void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
}
}


发现推出后马上切换行,过一分钟左右还是不行.

 

就郁闷了...到底缓存数据存在哪了呢...

最后google在stackoverflow上看到一篇文章,问题得以解决.原来是要清除webview的cookie才能彻底把缓存清除

public void clearWebViewCache() {
// 清除cookie即可彻底清除缓存
CookieSyncManager.createInstance(self);
CookieManager.getInstance().removeAllCookie();
}

 

附上两篇文章地址

http://stackoverflow.com/questions/2465432/Android-webview-completely-clear-the-cache

http://www.devdiv.com/forum.PHP?mod=viewthread&tid=116641


========

Android应用注销会话后清除WebView中Cookies

 

Android应用使用WebView控件浏览网页,用户登录账户后会将Cookie存入/data/data/<package_name>/databases/webviewCookiesChromium.db的cookies表中。应用退出后不会自动清理cookie,如果cookie过期时间长,可能存在安全风险,需要在注销登录时清除所有cookies。

private void removeCookie(Context context) {

CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
CookieSyncManager.getInstance().sync();
}

还可以修改指定cookie,删除缓存,参考以下链接:
http://blog.csdn.net/shichaosong/article/details/7949580

==================
##Android 清除WebView缓存

最近项目中需要用WebView显示内容,需要使用JavaScript去交互,但是每次加载都加载到了缓存的数据,这里记录一下如何去清除WebView缓存。

首先要了解一些感念。

WebView的缓存可以分为页面缓存和数据缓存.

####页面缓存 : >指加载一个网页时的html、JS、CSS等页面或者资源数据。 >这些缓存资源是由于浏览器的行为而产生,开发者只能通过配置HTTP响应头影响浏览器的行为才能间接地影响到这些缓存数据。 >缓存的索引存放在/data/data/package_name/databases下。 >文件存放在/data/data/package_name/cache/xxxwebviewcachexxx下。

####数据缓存 : >数据缓存分为AppCache和DOM Storage两种。 >这些缓存资源是由开发者的直接行为而产生,所有的缓存数据都由开发者直接完全地掌控。 >Android中Webkit使用一个db文件来保存AppCache数据(my_path/ApplicationCache.db) >Android中Webkit会为DOM Storage产生两个文件(my_path/localstorage/http_h5.m.taobao.com_0.localstorage和my_path/localstorage/Databases.db)。

具体可以参考Url……


####清理WebView缓存

1.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 2.context.deleteDatabase(“WebView.db”); 3.context.deleteDatabase(“WebViewCache.db”); 4.webView.clearCache(true); 5.webView.clearHistory(); 6.webView.clearFormData(); 7.getCacheDir().delete(); 8.用File的delete方法删除缓存文件夹;

PS:老实说,对我的问题,没多大用,还是那句话,有事请Google…

其实如果你只是想要每次用webView.loadUrl(url)加载新的页面显示,那么调用webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE)就可以实现了,并不需要去删除缓存文件什么的。

但是我的项目中使用了JavaScript的交互,而JavaScript的加载是通过头文件去获取加载的,所以每次我去获取新的页面的时候,虽然页面是新的,但是头文件中的数据还是old的,所以每次加载到的js都是old的。那么如何去做呢?

上面提到这个头文件是浏览器HTTP相应头去获取的,开发者只能间接的影响,并不能控制。

所以单独的webView.clearCache(true)是不能成功的,还需要清除webView的Cookie才行。

所以我最终的解决方法是在Activity的onDestroy()方法中添加如下代码:

@Override
protected void onDestroy() {
super.onDestroy();
//清空所有Cookie
CookieSyncManager.createInstance(QzmobileApp.getContext()); //Create a singleton CookieSyncManager within a context
CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
cookieManager.removeAllCookie();// Removes all cookies.
CookieSyncManager.getInstance().sync(); // forces sync manager to sync now

webView.setWebChromeClient(null);
webView.setWebViewClient(null);
webView.getSettings().setJavaScriptEnabled(false);
webView.clearCache(true);
}


CookieSyncManager已经@Deprecated,但是requires API level 21,所以……

PS:其实最好是把清除缓存的代码都封装到一个类,然后调用静态方法即可。

==============
在Android应用程序中经常会加载一个WebView页,如果需要客户端向WebView传递信息,比如Cookie,也是可以的。

需要应用程序先将Cookie注入进去,打开该网页时,WebView会将加载的url通过http请求传输到服务器。同时,在这次请求中,会将Cookie信息通过http header传递过去。

流程如下:

1、客户端通过以下代码设置cookie
public static void synCookies(Context context, String url) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(url, "uid=1243432");
CookieSyncManager.getInstance().sync();
}

2、CookieManager会将这个Cookie存入该应用程序/data/data/databases/目录下的webviewCookiesChromium.db数据库的cookies表中


3、打开网页,WebView从数据库中读取该cookie值,放到http请求的头部,传递到服务器

4、客户端可以在注销登录时清除该应用程序用到的所有cookies
private void removeCookie(Context context) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
CookieSyncManager.getInstance().sync();
}

==============


1.It does however, get called when the WebView to load a different URL from the one the user had requested.


2.Calling loadUrl() will also trigger the shouldOverrideUrlLoading() method. (Only when a new url is about to be loaded.)

 

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.

Ref : public boolean shouldOverrideUrlLoading (WebView view, String url)

===========

Use
getOriginalUrl ()

It returns the URL that was originally requested for the current page

getUrl () is not always the same as the URL passed to WebViewClient.onPageStarted because although the load for that URL has begun, the current page may not have changed.

getOriginalUrl () gets the original URL for the current page. This is not always the same as the URL passed to WebViewClient.onPageStarted because although the load for that URL has begun, the current page may not have changed. Also, there may have been redirects resulting in a different URL to that originally requested.

webview 缓存

标签:

原文地址:http://www.cnblogs.com/dennysong/p/5581530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!