2017-10-10 32 views
0

请对Java非常新颖,我试图把我的网站放在webview中,我有几行代码将用户发送到电子邮件表单并且工作得很好。但是,现在我必须在3个以上的地方使用相同的代码,当url匹配的东西,我知道会有一种方法把这个代码作为一个功能的地方,然后调用它,我想要使用它的时间。请有人可以帮助我。如何为android webview创建可重用的java函数

function RequestMailForm(newbody, newsubject, newemailto, newmailbbc){ 
    /* That email code*/ 
    } 
    mva.setWebViewClient(new WebViewClient() { 
    if (url.startsWith("mailto:")) { 
     url = url.substring(7); 
     String body = "Body of message."; 
     Intent mail = new Intent(Intent.ACTION_SEND); 
     mail.setType("application/octet-stream"); 
     mail.putExtra(Intent.EXTRA_EMAIL, new String[] { url }); 
     mail.putExtra(Intent.EXTRA_SUBJECT, "Subject"); 
     mail.putExtra(Intent.EXTRA_TEXT, body); 
     startActivity(mail); 
     return true; 
    } 
    if (url.startsWith("http://example.com/help") || url.startsWith("https://example.com/contact")){ 
     RequestMailForm(newbody, newsubject, newemailto, newmailbbc); 
    } 
}); 
+0

什么阻碍你把你的代码(这是应该被重新 - 使用)到一个类? –

+0

@ B001请告诉我如何,因为我也不知道如何做到这一点,我创建了一个新的Java类,但我如何编码它来传递新的电子邮件和消息正文等,我想它 – Peter

+0

_wast资源..._?你在谈论字节吗? –

回答

1

创建一个类,并将sendEmail方法与消息和电子邮件参数。 请参阅下面的代码。

class SendEmail { 
    Context context; 

    public SendEmail(Context context){ 
     this.context = contex; 
    } 

    //send an email 
    public void send(String email) { 
     Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
     "mailto", email, null)); 
     intent.setType("message/rfc822"); 
     intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); 
     intent.putExtra(Intent.EXTRA_TEXT, "Body of message"); 
     context.startActivity(Intent.createChooser(emailIntent, "Send email...")); 
    } 
} 

则每次创建SendEmail类的一个对象,并调用该函数要发送这样的邮件:

if (url.startsWith("mailto:")) { 
    url = url.substring(7); 
    sendEmail.send(url); 
    return true; 
} 
相关问题