summaryrefslogtreecommitdiffstats
path: root/mobile/android/base/java/org/mozilla/gecko/ActivityHandlerHelper.java
blob: 7174c658077e810ea91a20cba628ff2bd98493a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko;

import org.mozilla.gecko.util.ActivityResultHandler;
import org.mozilla.gecko.util.ActivityResultHandlerMap;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ActivityHandlerHelper {
    private static final String LOGTAG = "GeckoActivityHandlerHelper";
    private static final ActivityResultHandlerMap mActivityResultHandlerMap = new ActivityResultHandlerMap();

    private static int makeRequestCode(ActivityResultHandler aHandler) {
        return mActivityResultHandlerMap.put(aHandler);
    }

    public static void startIntent(Intent intent, ActivityResultHandler activityResultHandler) {
        startIntentForActivity(GeckoAppShell.getGeckoInterface().getActivity(), intent, activityResultHandler);
    }

    /**
     * Starts the Activity, catching & logging if the Activity fails to start.
     *
     * We catch to prevent callers from passing in invalid Intents and crashing the browser.
     *
     * @return true if the Activity is successfully started, false otherwise.
     */
    public static boolean startIntentAndCatch(final String logtag, final Context context, final Intent intent) {
        try {
            context.startActivity(intent);
            return true;
        } catch (final ActivityNotFoundException e) {
            Log.w(logtag, "Activity not found.", e);
            return false;
        } catch (final SecurityException e) {
            Log.w(logtag, "Forbidden to launch activity.", e);
            return false;
        }
    }

    public static void startIntentForActivity(Activity activity, Intent intent, ActivityResultHandler activityResultHandler) {
        activity.startActivityForResult(intent, mActivityResultHandlerMap.put(activityResultHandler));
    }


    public static boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        ActivityResultHandler handler = mActivityResultHandlerMap.getAndRemove(requestCode);
        if (handler != null) {
            handler.onActivityResult(resultCode, data);
            return true;
        }
        return false;
    }
}