我是一个制作android应用程序的初学者。我做了一个网页视图,显示我的网页。我的网页包含联系人按钮,我希望在邮件和拨号等外部应用程序中打开这些按钮。所以我得到了一些帮助,得到了这样的代码

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..."));

}

}

但后来我得到一个错误“找不到符号方法startActivity(android.content.intent)”,startActivity有什么问题?

最佳答案

WebViewClient没有上下文,因此无法直接启动活动

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);

或者,使用WebViewClient的构造函数将上下文传递给它
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;
}

关于java - 找不到符号方法startActivity(android.content.Intent),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23872245/

10-10 19:22