summaryrefslogtreecommitdiffstats
path: root/mobile/android/base/java/org/mozilla/gecko/prompts/PromptService.java
blob: 8155cc1c64a8a2e5ccbe7a9d83605cdd06e2b513 (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
62
63
64
65
66
67
68
69
70
71
72
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * 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.prompts;

import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.gecko.EventDispatcher;
import org.mozilla.gecko.GeckoApp;
import org.mozilla.gecko.GeckoAppShell;
import org.mozilla.gecko.util.GeckoEventListener;
import org.mozilla.gecko.util.ThreadUtils;

import android.content.Context;
import android.util.Log;

public class PromptService implements GeckoEventListener {
    private static final String LOGTAG = "GeckoPromptService";

    private final Context mContext;

    public PromptService(Context context) {
        GeckoApp.getEventDispatcher().registerGeckoThreadListener(this,
            "Prompt:Show",
            "Prompt:ShowTop");
        mContext = context;
    }

    public void destroy() {
        GeckoApp.getEventDispatcher().unregisterGeckoThreadListener(this,
            "Prompt:Show",
            "Prompt:ShowTop");
    }

    public void show(final String aTitle, final String aText, final PromptListItem[] aMenuList,
                     final int aChoiceMode, final Prompt.PromptCallback callback) {
        // The dialog must be created on the UI thread.
        ThreadUtils.postToUiThread(new Runnable() {
            @Override
            public void run() {
                Prompt p;
                p = new Prompt(mContext, callback);
                p.show(aTitle, aText, aMenuList, aChoiceMode);
            }
        });
    }

    // GeckoEventListener implementation
    @Override
    public void handleMessage(String event, final JSONObject message) {
        // The dialog must be created on the UI thread.
        ThreadUtils.postToUiThread(new Runnable() {
            @Override
            public void run() {
                Prompt p;
                p = new Prompt(mContext, new Prompt.PromptCallback() {
                    @Override
                    public void onPromptFinished(String jsonResult) {
                        try {
                            EventDispatcher.sendResponse(message, new JSONObject(jsonResult));
                        } catch (JSONException ex) {
                            Log.i(LOGTAG, "Error building json response", ex);
                        }
                    }
                });
                p.show(message);
            }
        });
    }
}