I have an app with a webview. The webview links to a mobile webpage where all links work correctly. When I click on a link in this webview, the link opens up in google maps inside the webview. Instead, I want the link to open up the native google maps app. Can anyone tell me how to do this?
I have this code that I need to insert it to my code
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("geo:")) {
Uri gmmIntentUri = Uri.parse(url);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
return true;
}
view.loadUrl(url);
return true;
}
This is my code:
package com.company.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("www.google.com");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
}
}
To call android method from javascript you would need to make Javascriptinterface class and annotating method like #JavascriptInterface in documentation
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
and bind it to webview like
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
and from javascript you can call it like
function showtoastfromsite(){
Android.showToast("hello from website");
}
Related
I already make a java WebView for my website, this website in the footer the phone number and the email address when I click in it they told me (the webpage at tel could not be loaded because err_unknown_url_scheme), What should i do ?
MainActivity.Java
package xxx.xxxxxxx.xxxxxxxxx;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
Objects.requireNonNull(this.getSupportActionBar()).hide();
}
catch (NullPointerException ignored){}
//find the view
webView = findViewById(R.id.webview);
// to load all the web page in app itself use this
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.ezyadvs.com");
WebSettings webSettings =webView.getSettings();
//if your website is using any javascript that needs to load some script then you need to enable javascript in android application
webSettings.setJavaScriptEnabled(true);
}
#Override
public void onBackPressed() {
// if any previous webpage exist then onback pressed will take care of it
if(webView.canGoBack())
{
webView.goBack();
}else{
//else it will exit the application
super.onBackPressed();
}
}
}
Here is my solution in .kt (kotlin) :
this.webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
//add condition startsWith("tel:") or startsWith("mailto:")
if (url!!.startsWith("whatsapp:")) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
return true
}
return false
}
}
I have tried many things and keep receiving a crash error on my Android app. My app is a simple webwrapper app using the webview function. Basically, I have webview displaying a website that has a mobile site. What I am trying to do is make it so that
back button will take the user back to the previous screen
back button on the app (which I put in the layout), will also take the user to the previous screen.
I also want the home button on the phone to go back to the home screen and exit the app completely.
Lastly, the mobile app has external links that should be going into a browser and not staying within the app (example: visit full site).
Below is my code, any help for any of the 1-4 questions would be helpful! :-)! If you need to see my XML dont hesitate to ask.
package com.example.envision;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class Envision extends Activity {
/** back button functionality NOT WORKING CAUSES A CRASH
WebView webview;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
} */
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_envision);
WebView webview = (WebView) findViewById(R.id.webView1);
WebSettings websettings = webview.getSettings();
websettings.setJavaScriptEnabled(true);
websettings.setSaveFormData(false);
websettings.setSavePassword(false);
webview.loadUrl("http://envisionfinancial.ca/m/");
webview.setHorizontalScrollBarEnabled(false);
webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setBackgroundColor(128);
webview.setWebViewClient(new EnvisionWebViewClient());
webview.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);
}
});
}
public void visible(){
WebView webview = (WebView) findViewById(R.id.webView1);
ImageView logo = (ImageView) findViewById(R.id.imageView1);
ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar1);
webview.setVisibility(10);
logo.setVisibility(0);
bar.setVisibility(0);
}
public void unvisible(){
WebView webview = (WebView) findViewById(R.id.webView1);
ImageView logo = (ImageView) findViewById(R.id.imageView1);
ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar1);
webview.setVisibility(0);
logo.setVisibility(10);
bar.setVisibility(10);
}
private class EnvisionWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url){
webview.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
view.loadUrl("http://envisionfinancial.ca/m/");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
visible();
}
#Override
public void onPageFinished(WebView view, String url) {
unvisible();
}
}
/** exits the app?? review */
public void finishActivity(View v) {
finish();
}
}
Are you getting a NullPointerException in onKeyDown? That is because you do not assign the WebView to the instance variable:
webview = (WebView) findViewById(R.id.webView1);
The back functionality can be implemented like this:
public void onBackPressed() {
if (webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
See this :
http://developer.android.com/guide/webapps/webview.html
Scroll to Binding JavaScript code to Android code
http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
I have a simple webview which loads a page. This page has a few links that opens within the webview. That's what it supposed to do, so it's working all fine.
But there is one single link from that page which should load as a popup, so I want it to open in the normal browser when people click it. But as I stated, all links are opening in the webview, so that link does it also.
My question is, how can I make this link open in the normal browser as a kind of a popup? Is it even possible? The link is variable so it's changing always, it cannot be hardcoded within the application to open in a new browser browser.
Is it possible and how can I do it?
Here's an example of overriding webview loading to stay within your webview or to leave:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class TestWebViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
}
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("somePartOfYourUniqueUrl")){ // Could be cleverer and use a regex
return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
} else {
view.loadUrl(url); // Stay within this webview and load url
return true;
}
}
}
public class WebViewActivity extends Activity {
private WebView webView;
private ProgressDialog progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.loadUrl("https://www.example.com");
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("https://www.example.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;
}
}
}
I'm trying to use the Android tutorial to build an app that loads a web view to a mobile site that I built. The problem is with following the tutorial the startActivity function is undefined and the Android tutorial isn't helping. I've done Ctrl+Shift+O to verify all the proper modules are loaded.
package com.mysite;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.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;
}
}
Update
Ok, now my code reads:
package com.myapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MyApp extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init webview
WebView DCWebView = (WebView) findViewById(R.id.webview);
WebSettings webViewSettings = DCWebView.getSettings();
//when a link is clicked, use the WebView instead of opening a new browser
DCWebView.setWebViewClient(new MyWebViewClient() {
#Override
public void launchExternalBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
//enable javascript
webViewSettings.setJavaScriptEnabled(true);
}
}
But I'm showing 2 errors:
Description Resource Path Location Type
The type new MyWebViewClient(){} must implement the inherited abstract method MyWebViewClient.launchExternalBrowser() DealClippings.java /MyApp/src/com/myapp line 21 Java Problem
The method launchExternalBrowser(String) of type new MyWebViewClient(){} must override or implement a supertype method MyApp.java /DealClippings/src/com/myapp line 23 Java Problem
There really is no startActivity method for WebViewClient. You can check the docs. You'll have to signal the Context (probably your Activity) to execute those lines of code instead. There are many possible approaches including adding listeners or simply calling an abstract method which you implement in an anonymous instance of this class when setting the WebViewClient of your WebView in your Activity.
For example:
public abstract class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
launchExternalBrowser(url);
return true;
}
public abstract void launchExternalBrowser(String url);
}
And then in your activity:
WebViewClient client = new MyWebViewClient() {
#Override
public void launchExternalBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
};
Although I'm not sure why you want this behavior exactly, but it should work more or less.
I don't know if there's much point answering your edit now, 18 months on, but it seems like this question gets a bit of traffic so I'll post this here for posterity.
From your errors, it sounds like you haven't provided an argument to the abstract method in the abstract class definition of MyWebViewClient. That is, you have this:
public abstract void launchExternalBrowser();
when you should have this:
public abstract void launchExternalBrowser(String url);
The cause of the error is that Java treats two methods with the same name but different arguments as two distinct methods. So launchExternalBrowser(String) is a different method to launchExternalBrowser().
Hope this helps someone!
To answer original question before your edit..
Had the same problem, and figured out that the MyWebViewClient is meant to be an inner class inside the activity.
package com.myapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyApp extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init webview
WebView DCWebView = (WebView) findViewById(R.id.webview);
WebSettings webViewSettings = DCWebView.getSettings();
//when a link is clicked, use the WebView instead of opening a new browser
DCWebView.setWebViewClient(new MyWebViewClient());
//enable javascript
webViewSettings.setJavaScriptEnabled(true);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.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;
}
}
}
I have the following code that is working but when I hit the hardware back button the app crashes,
package com.fnesse.tmpmobile;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
#SuppressWarnings("unused")
public class TmpmobileActivity extends Activity
{
WebView webView;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setBackgroundColor(0x00000000);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
//Error Code Here
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.themorningtonpeninsula.com");
}
#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 found somewhere that I needed to add,
WebView webView;
Above the onCeate method, which allowed webView to resolve. So now I get no errors but it crashes and the app runs on my phone but crashes when I hit the hardware back button.
Does anyone know why that would be happening?
Cheers,
Mike.
I'll try to do my magic guest on the error message. I think, this error is caused by the way to initialize webView variable. You see, on the class level, you declare:
WebView webView;
And then, on onCreate() you initialize webView and also redeclare it again:
WebView webView = (WebView) findViewById(R.id.webview);
But, this redeclare step resulted in class level webView to be uninitialized.
To fix it, try to change this line:
WebView webView = (WebView) findViewById(R.id.webview);
Into:
webView = (WebView) findViewById(R.id.webview);
And you should now have class level webView initialized and ready for use in whatever method you have.
Here's few resources explaining Java variable scope:
http://www.java-made-easy.com/variable-scope.html
http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm
You are creating a new Webview in your onCreate() method instead of the Class field Webview. Change
WebView webView = (WebView) findViewById(R.id.webview);
into:
webView = (WebView) findViewById(R.id.webview);