I've added a webview activity and would like to control which folder any downloaded that my end users will download via my app. The files will be pdf files and I would like them to go into a specific folder that my app uses rather than the default download folder.
public class myweb extends Activity {
private WebView myWebView;
private String LOG_TAG = "AndroidWebViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.knitweb);
myWebView = (WebView) findViewById(R.id.webView1);
//enable Javascript
myWebView.getSettings().setJavaScriptEnabled(true);
//loads the WebView completely zoomed out
myWebView.getSettings().setLoadWithOverviewMode(true);
//true makes the Webview have a normal viewport such as a normal desktop browser
//when false the webview will have a viewport constrained to it's own dimensions
myWebView.getSettings().setUseWideViewPort(true);
//override the web client to open all links in the same webview
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebChromeClient(new MyWebChromeClient());
//Injects the supplied Java object into this WebView. The object is injected into the
//JavaScript context of the main frame, using the supplied name. This allows the
//Java object's public methods to be accessed from JavaScript.
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
//load the home page URL
//myWebView.loadUrl("http://demo.mysamplecode.com/Servlets_JSP/pages/androidWebView.jsp");
myWebView.loadUrl("http://www.patonsyarns.com/pattern.php?PID=4521&cps=21191");
myWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("demo.mysamplecode.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
private class MyWebChromeClient extends WebChromeClient {
//display alert message in Web View
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
new AlertDialog.Builder(view.getContext())
.setMessage(message).setCancelable(true).show();
result.confirm();
return true;
}
}
public class JavaScriptInterface {
Context mContext;
// Instantiate the interface and set the context
JavaScriptInterface(Context c) {
mContext = c;
}
//using Javascript to call the finish activity
public void closeMyActivity() {
finish();
}
}
//Web view has record of all pages visited so you can go back and forth
//just override the back button to go back in history if there is page
//available for display
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
I do not know in advance which files the users will be downloading other than that they will be pdf files.
Any help would be great
Thanks
I’m affraid the only solution is to use DownloadListener to catch the event and download the file manually.
Download a file example: http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
DownloadListener example: How do I use DownloadListener?
Related
I developed a simple app that has two activities. When I call Menu activity to Webview using intent, it opens very well in web view, but when I click the button to return back to Activity, it crashes and asks to "close the app." Below is my java and it looks fine without errors. The log cat as well doesn't display any errors.
Who has the solution to these?
public class WebView extends AppCompatActivity {
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
String url = getIntent().getStringExtra("site_url");
android.webkit.WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("" + url);
}
private class MywebClient extends WebViewClient {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
}
#Override
public void onBackPressed() {
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
{
webView.goBack();
}else{
super.onBackPressed();
}
}
}
Your problem is right here, in onBackPressed():
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
You set the variable webView to null and then you call a method isFocused() on it. That will cause a NullPointerException.
Change this to:
android.webkit.WebView webView = findViewById(R.id.webView);
if(webView.isFocused() && webView.canGoBack())
"How to open .ppt, .pptx,.doc, .xlsx files in android webview within app?"
"This is requirement to open any documents which i have download in sd card and open witin android webview. In the past I have tried lot of google suggested answer which they are open file outside the app using intent and MIME Type or open online file like webview.loadUrl("http://docs.google.com/gview?embedded=true&url=http://myurl.com/mySlide.ppt");"
public class WebContentViewActivity extends BaseActivity {
#BindView(R.id.webView)
WebView webView;
private String docUrl="http://docs.google.com/gview?
embedded=true&url=";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.VmPolicy.Builder builder = new
StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
setContentView(R.layout.activity_video_view);
ButterKnife.bind(this);
WebSettings settings = webView.getSettings();
webView.clearCache(true);
webView.clearHistory();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebViewClient(new WebViewController(this));
filePath =
"/storage/emulated/0/New_Files/1550130536314somefile.pptx";
fileName = "1550130536314somefile.pptx";
if (!TextUtils.isEmpty(fileName )){
Uri fileUri = Uri.fromFile(fileName );
webView.loadUrl(fileUri.toString());
// webView.loadUrl(docUrl+fileUri);//getting 400.That's an error
on webview
}
/**
* Custom WebView controller class
*/
private class WebViewController extends WebViewClient {
private Context mContext;
//TODO : use this flag while open clicked url in the same WebView
public WebViewController(Context ctx) {
this.mContext = ctx;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("onPageStarted: " + url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.v("Webview Error", description);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
{
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I want to show any document file witin webview as above in the code.
I have a webView in Android and I open a html webpage in it. But it's full of links and images: when I click one of them it loads in my webview.I want to disable this behaviour, so if I click on a link, don't load it and go back to the first page.
I've tried this solution and edited a bit for myself, but it does not work:
webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));
This opens a white page but I want to open the main URL. My webviewclient code:
public class MainActivity extends Activity {
public static String URL = "http://www.example.com/";
private WebView webView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView = (WebView) findViewById(R.id.webview);
MyWebViewClient myWebViewClient = new MyWebViewClient();
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));
webView.reload();
webView.loadUrl(URL);
webSettings.setDisplayZoomControls(true);
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()){
webView.goBack();
return true;
}
break;
}
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}
else{
super.onBackPressed();
}
}
}
you need to overwrite onPageStarted in WebViewClient:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//here check url i.e equals to your that html page
// if url equals not load url
and for go to back page check:
if(view.canGoBack())
// load first page url
}
You need a WebViewClient that overrides loading url:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// url is the url to be loaded
return true; // override url (don't load it)
return false; // let url load
}
});
You can always return true to stay on the same page.
To open Main Url and stay on it, use this:
webview.loadUrl(MainUrl);
and then override loading url and always return true:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
In my app, there are four tabs and in the second tab, I am trying to load webview...
after disable shouldOverrideUrlLoading it perfectly load webview in fragment...
but with shouldOverrideUrlLoading method, it redirects on new activity...
But what I want is to load webview first on fragment and after clicking on any content link it should be redirected on new activity
private void setUpWebView() {
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
webView.setScrollContainer(false);
webView.setWebViewClient(new WebViewClient());
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
private class WebViewClient extends android.webkit.WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
Intent intent = new Intent(getContext(),WebViewShowActivity.class);
startActivity(intent);
return true;
}
}
You can check condition
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
if (view.getUrl()!=baseUrl) {
Intent intent = new Intent(getContext(), WebViewShowActivity.class);
startActivity(intent);
return true;
}else {
return false;
}
}
To load url in webview you should load it in webview object returned in callback that is "view" and to open clicked links from webview content you should check request and load that in new activity.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String request) {
if (request != null && request.toString().startsWith("http://")) { //comparison params is upto your requirements
Intent intent = new Intent(MainActivity.this, secondactivity.class);
startActivity(intent);
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}
});
public class WebViewJavaScriptInterface {
public Context context;
public WebViewJavaScriptInterface(Context context) {
this.context = context;
}
#JavascriptInterface
public void openPost(String url,String posttitle) {
String postUrl = "https://google.in"+url;
String postTitle = posttitle;
Log.d("POSTURL",postUrl);
Intent intent = new Intent(getContext(), WebViewShowActivity.class);
intent.putExtra("linkUrl",postUrl);
intent.putExtra("postTitle",postTitle);
startActivity(intent);
}
#JavascriptInterface
public void openVideo(String url) {
String youtubeUrl = url;
Log.d("YoutubeURL",youtubeUrl);
ForTrainertUtil.playPostVideoForYoutubeID(context,youtubeUrl);
}
}
this is how we can handle click event from web page through JavaScript..
when I click on a specific content of web page it handle associate method in android.
I'm trying to make an app that opens all web pages of a certain site, for example www.yahoo.com, in the webview, but all other web pages in the defaultbrowser. Here is the code that I am using but can not quite get it work.
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://www.yahoo.com")) {
// This is my web site, so do not override; let my WebView load
// the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
It looks to me that this code should work, but when i load yahoo it still goes to an outside browser. Any help would be appreciated. Thanks!
Here is a different way to do it.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String urlHost = Uri.parse(url).getHost();
switch (urlHost) {
case "yahoo.com":
return false;
case "www.yahoo.com":
return false;
case "m.yahoo.com":
return false;
default:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
getHost() usually returns just the domain name, or sometimes with www. prefixed to it. It never contains an http:// protocol AFAIK. Try using:
if ((Uri.parse(url).getHost().equals("yahoo.com")) || (Uri.parse(url).getHost().equals("www.yahoo.com")) || (Uri.parse(url).getHost().equals("m.yahoo.com"))) {
//Your code
Try this it should help you
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yahoo);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#TargetApi(android.os.Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("http://www.yahoo.com");
setContentView(mWebview );
}
}