找不到符号方法startActivity(android.content.Intent)

时间:2014-05-26 14:19:28

标签: java android start-activity

我是制作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)"开始活动有什么问题?

1 个答案:

答案 0 :(得分:5)

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;
}