1// Copyright 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package org.chromium.chrome.browser;
6
7import android.accounts.Account;
8import android.accounts.AccountManager;
9import android.content.Context;
10import android.content.Intent;
11import android.net.Uri;
12import android.text.Html;
13import android.text.TextUtils;
14import android.util.Patterns;
15
16import org.chromium.base.CalledByNative;
17
18import java.io.File;
19import java.util.HashSet;
20import java.util.Set;
21import java.util.regex.Pattern;
22
23/**
24 * Helper for issuing intents to the android framework.
25 */
26public abstract class IntentHelper {
27
28    private IntentHelper() {}
29
30    /**
31     * Triggers a send email intent.  If no application has registered to receive these intents,
32     * this will fail silently.
33     *
34     * @param context The context for issuing the intent.
35     * @param email The email address to send to.
36     * @param subject The subject of the email.
37     * @param body The body of the email.
38     * @param chooserTitle The title of the activity chooser.
39     * @param fileToAttach The file name of the attachment.
40     */
41    @CalledByNative
42    static void sendEmail(Context context, String email, String subject, String body,
43            String chooserTitle, String fileToAttach) {
44        Set<String> possibleEmails = new HashSet<String>();
45
46        if (!TextUtils.isEmpty(email)) {
47            possibleEmails.add(email);
48        } else {
49            Pattern emailPattern = Patterns.EMAIL_ADDRESS;
50            Account[] accounts = AccountManager.get(context).getAccounts();
51            for (Account account : accounts) {
52                if (emailPattern.matcher(account.name).matches()) {
53                    possibleEmails.add(account.name);
54                }
55            }
56        }
57
58        Intent send = new Intent(Intent.ACTION_SEND);
59        send.setType("message/rfc822");
60        if (possibleEmails.size() != 0) {
61            send.putExtra(Intent.EXTRA_EMAIL,
62                    possibleEmails.toArray(new String[possibleEmails.size()]));
63        }
64        send.putExtra(Intent.EXTRA_SUBJECT, subject);
65        send.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
66        if (!TextUtils.isEmpty(fileToAttach)) {
67            File fileIn = new File(fileToAttach);
68            send.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileIn));
69        }
70
71        try {
72            Intent chooser = Intent.createChooser(send, chooserTitle);
73            // we start this activity outside the main activity.
74            chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
75            context.startActivity(chooser);
76        } catch (android.content.ActivityNotFoundException ex) {
77            // If no app handles it, do nothing.
78        }
79    }
80}
81