问题
I'd like to start a WebView
from my AsyncTask
but it doesn't seem to run. This is what my onPostExecute
method looks like:
public class Viewer extends AsyncTask<URI, Integer, URI> {
private Activity objContext = null;
public Viewer(Activity objContext) {
this.objContext = objContext;
}
protected void onPostExecute(URI uriWebpage) {
WebView wbvBrowser = new WebView(this.objContext);
wbvBrowser.getSettings().setBuiltInZoomControls(true);
wbvBrowser.getSettings().setJavaScriptEnabled(true);
wbvBrowser.loadUrl(uriWebpage.toString());
}
}
My task is used by two activities in my application and therefore my global objContext
variable is of type Activity
. If I change the type of my objContext
variable to the name of the calling class, it works fine but then I can't instantiate my task from the other calling class. I instantiate my task like this.
Viewer mytask = new Viewer(this);
How can I solve this?
回答1:
Did you setContentView
from original layout to webView or you have a container to put webview? otherwise I don't think webView UI appears.
回答2:
Are you sure you execute your AsyncTask
@Override
protected void onPostExecute(Void result){
}
}.execute();
Also need to class name
Viewer mytask = new Viewer(YourclassName.this);
// or This may Helps you
private Context mcontext;
public Viewer(Context objContext) {
this.mcontext= objContext;
}
protected void onPostExecute(URI uriWebpage) {
WebView wbvBrowser = new WebView(((Activity)(mcontext)));
}
回答3:
I have solved the issue. It has nothing to do with the use of Activity
or Context
. Both work just fine. Some URLs don't seem to load the WebView
. I changed the URL of the WebView
to point to a site like Google and it worked just fine. Seems like if the URL is incorrect, the WebView
doesn't throw an exception but doesn't open up either.
回答4:
I don't know why this happens, but why don't you just start the built in web browser through an Intent
in your onPostExecute(Uri uriWebpage)
?
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uriWebPage);
startActivity(intent);
If this solution doesn't satisfy you, then please post the error stack trace from LogCat.
来源:https://stackoverflow.com/questions/12302194/unable-to-start-a-webview-from-an-asynctask