I am a beginner in making android applications. I have made a web view which shows my web page. My web page consists contact buttons that i want to be opened in external apps like mail and dial. Therefore i got some help and got a code like this
import android.app.Activity;
import android.content.Intent;
import android.net.MailTo;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ourViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try{
System.out.println("url called:::" + url);
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
} else if (url.startsWith("http:")
|| url.startsWith("https:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} else if (url.startsWith("mailto:")) {
MailTo mt=MailTo.parse(url);
send_email(mt.getTo());
}
else {
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}
public void send_email(String email_add) {
System.out.println("Email address::::" + email_add);
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { email_add });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
startActivity(
Intent.createChooser(emailIntent, "Send mail..."));
}
}
But then i got this error "Cannot find symbol method startActivity(android.content.Intent)" What is wrong with the startactivity?
WebViewClient
doesn't have context so you cannot directly start an activity
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
Alternatively, pass context to webViewClient using its constructor
public class ourViewClient extends WebViewClient {
Context context;
public ourViewClient (Context c){
this.context = c;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try{
System.out.println("url called:::" + url);
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
context.startActivity(intent);
} else if (url.startsWith("http:")
|| url.startsWith("https:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} else if (url.startsWith("mailto:")) {
MailTo mt=MailTo.parse(url);
send_email(mt.getTo());
}
else {
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}