Example usage for android.content Intent setFlags

List of usage examples for android.content Intent setFlags

Introduction

In this page you can find the example usage for android.content Intent setFlags.

Prototype

public @NonNull Intent setFlags(@Flags int flags) 

Source Link

Document

Set special flags controlling how this intent is handled.

Usage

From source file:com.safecell.ManageProfile_Activity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {

        if (callingActivity.equals("SettingScreenActivity")) {
            Intent homeScreen = new Intent(ManageProfile_Activity.this, SettingScreenActivity.class);
            homeScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(homeScreen);//w ww .  j  a  v a2 s . co m
            finish();
        } else if (callingActivity.equals("AccountActivity")) {
            Intent homeScreen = new Intent(ManageProfile_Activity.this, AccountActivity.class);
            homeScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            homeScreen.putExtra("Account_Activity_Calling", "From manage profile activity");
            startActivity(homeScreen);
            finish();
        }
    }
    return false;

}

From source file:org.kaoriha.phonegap.plugins.releasenotification.Notifier.java

private void pollBackground() {
    if (getToken() == null) {
        rescheduleAfterFail();/*w  ww  . j  a  va  2s  .  com*/
        return;
    }

    ToNextReleasePolling tp = new ToNextReleasePolling();
    tp.poll();
    if (tp.isFailed) {
        Log.d(TAG, "ToNextReleasePolling failed");
        rescheduleAfterFail();
        return;
    }

    CataloguePolling cp = new CataloguePolling();
    cp.poll();
    if (cp.isFailed) {
        Log.d(TAG, "CataloguePolling failed");
        rescheduleAfterFail();
        return;
    }
    if (!cp.isNew) {
        if (tp.toNextRelease == -1) {
            schedule(RESCHEDULE_NEXT_UNKNOWN_SPAN);
        } else {
            schedule(tp.toNextRelease);
        }
        Log.d(TAG, "CataloguePolling not new");
        return;
    }

    String pushMessage;
    if (cp.catalogue.has(CATALOGUE_PUSH_MESSAGE_KEY)) {
        try {
            pushMessage = cp.catalogue.getString(CATALOGUE_PUSH_MESSAGE_KEY);
        } catch (JSONException e) {
            Log.i(TAG, "pollBackground()", e);
            pushMessage = pref.getString(SPKEY_DEFAULT_PUSH_MESSAGE, null);
        }
    } else {
        pushMessage = pref.getString(SPKEY_DEFAULT_PUSH_MESSAGE, null);
    }

    String lastSid;
    try {
        lastSid = getLastSid(cp.catalogue);
        if (lastSid.equals(pref.getString(SPKEY_LAST_SID, null))) {
            schedule(tp.toNextRelease);
        }
    } catch (JSONException e) {
        Log.d(TAG, "bad JSON", e);
        rescheduleAfterFail();
        return;
    }

    int icon = R.drawable.notification;
    Notification n = new Notification(icon, pushMessage, System.currentTimeMillis());
    n.flags = Notification.FLAG_AUTO_CANCEL;
    Intent i = new Intent(ctx, FlowerflowerActivity.class);
    i.setAction(Intent.ACTION_MAIN);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pi = PendingIntent.getActivity(ctx, 0, i, 0);
    n.setLatestEventInfo(ctx.getApplicationContext(), pref.getString(SPKEY_TITLE, null), pushMessage, pi);
    NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, n);

    pref.edit().putString(SPKEY_LAST_SID, lastSid).putString(SPKEY_LAST_CATALOGUE_ETAG, cp.etag).commit();

    clearFailRepeat();

    schedule(tp.toNextRelease);

    Log.d(TAG, "pollBackground() success");
}

From source file:abanoubm.dayra.main.Main.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == FOLDER_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.setDataAndType(Uri.fromFile(new File(Utility.getDayraFolder())), "*/*");
            startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
        }//w  w  w .ja v  a 2s .c o m

    } else if (requestCode == IMPORT_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            importDB();

    }
}

From source file:com.android.yijiang.kzx.http.AsyncHttpResponseHandler.java

final public void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBytes) {
    String content = new String(responseBytes);
    if (content.indexOf("invalid key") != -1 || content.indexOf("token missing") != -1) {
        if (ApplicationController.mCount > 0) {
            return;
        }//w w w.j  a va  2  s . c om
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                ApplicationController.mCount++;
                MsgTools.toast(ApplicationController.getInstance(), "?,?!",
                        Toast.LENGTH_LONG);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gotoLogin();
                    }
                }, Toast.LENGTH_SHORT);
                ApplicationController.mCount = 0;
                Looper.loop();
            }
        }).run();
    } else if (content.indexOf("need team") != -1) {
        Intent i = new Intent(ApplicationController.getInstance(), ContentFragmentActivity.class);
        i.putExtra("action", "create_team");
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        ApplicationController.getInstance().startActivity(i);
    } else {
        try {
            final boolean success = new JSONObject(content).optBoolean("success", false);
            final String message = new JSONObject(content).optString("message");
            final String data = new JSONObject(content).optString("data");
            if (!success && "null".equals(data) && StringUtils.isEmpty(message)) {
                gotoLogin();
                return;
            } else if (!success && "null".equals(data) && !StringUtils.isEmpty(message)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        MsgTools.toast(ApplicationController.getInstance(), message, Toast.LENGTH_LONG);
                        sendFinishMessage();
                        Looper.loop();
                    }
                }).run();
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { statusCode, headers, responseBytes }));
        }
        sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[] { statusCode, headers, responseBytes }));
    }
}

From source file:com.digi.android.wva.VehicleInfoService.java

/**
 * Depending on if the service is currently set as 'connected'
 * (check value of {@code isConnected} boolean), either call
 * {@link #startForeground(int, Notification)} to put up the
 * "service is running" notification, or call
 * {@link #stopForeground(boolean) stopForeground(true)} to remove the
 * notification (because the service isn't listening).
  */*  w  w w .  j  av  a2 s. co  m*/
  * <p>This method is protected, rather than private, due to a bug between JaCoCo and
  * the Android build tools which causes the instrumented bytecode to be invalid when this
  * method is private:
  * http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode
  * </p>
 */
protected void showNotificationIfRunning() {
    // First, c
    WvaApplication app = (WvaApplication) getApplication();
    if (app != null && app.isTesting())
        return;

    if (isConnected) {
        NotificationCompat.Builder builder;
        builder = new NotificationCompat.Builder(getApplicationContext());
        PendingIntent contentIntent;
        Intent intent = new Intent(VehicleInfoService.this, DashboardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        contentIntent = PendingIntent.getActivity(VehicleInfoService.this, 0, intent, 0);
        builder.setContentTitle("Digi WVA Service")
                .setContentText("Connected to " + (TextUtils.isEmpty(connectIp) ? "(null)" : connectIp))
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setSmallIcon(R.drawable.notif_small).setOngoing(true).setContentIntent(contentIntent);

        startForeground(NOTIF_ID, builder.build());
    } else {
        try {
            stopForeground(true);
        } catch (Exception e) {
            // Might happen if startForeground not called before
            e.printStackTrace();
        }
    }
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

private Intent createIntent(String intentAction, String intentUri, String intentType, String intentExtras) {
    Intent launchIntent;
    if (intentUri.equalsIgnoreCase("")) {
        launchIntent = getPackageManager().getLaunchIntentForPackage(intentAction);
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } else {// w  ww.  j a  v a  2s .com
        launchIntent = new Intent(intentAction, Uri.parse(intentUri));
    }
    if (!intentType.equalsIgnoreCase(""))
        launchIntent.setType(intentType);
    if (!intentExtras.equalsIgnoreCase("")) {
        try {
            JSONObject intentExtrasDict = new JSONObject(intentExtras);
            Iterator<?> keys = intentExtrasDict.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                launchIntent.putExtra(key, intentExtrasDict.get(key).toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return launchIntent;
}

From source file:com.eeshana.icstories.activities.UploadVideoActivity.java

@SuppressLint("NewApi")
@Override/*from w  w  w  .  ja  v  a2 s  .c om*/
public void onClick(View v) {
    if (v.getId() == uploadButton.getId()) {
        if (connectionDetector.isConnectedToInternet()) {
            title = titleEditText.getText().toString();
            description = descriptionEditText.getText().toString();
            flag = isAssignment;
            my_location = locationEditText.getText().toString();
            if (title.equalsIgnoreCase("") || description.equalsIgnoreCase("")) {
                showCustomToast.showToast(UploadVideoActivity.this, "Title and Description both are required");
            } else {

                Log.e("location2", my_location);

                //new UplodTask(getApplicationContext()).execute();
                if (title.length() <= 30 && title.length() >= 4 && description.length() >= 4
                        && description.length() <= 150 && my_location.length() <= 30) {//&& my_location.matches(pattern) && title.matches(pattern) && description.matches(pattern)){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        new UplodTask(getApplicationContext())
                                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    } else {
                        new UplodTask(getApplicationContext()).execute();
                    }

                } else {
                    //                  if(!title.matches(pattern)){
                    //                     titleEditText.setError("Title contains one or more invalid characters. Please check.");
                    //                  }
                    //                  if(!description.matches(pattern)){
                    //                     descriptionEditText.setError("Description contains one or more invalid characters. Please check");
                    //                  }
                    //                  if(!my_location.matches(pattern)){
                    //                     locationEditText.setError("Location contains one or more invalid characters. Please check");
                    //                  }
                    if (title.length() < 4) {
                        titleEditText.setError("Title must be min 4 characters.");
                    }
                    if (description.length() < 4) {
                        descriptionEditText.setError("Description must be min 4 characters.");
                    }
                    if (title.length() > 30) {
                        titleEditText.setError("Title must be max 30 characters.");
                    }
                    if (description.length() > 150) {
                        descriptionEditText.setError("Description must be max 150 characters.");
                    }
                    if (my_location.length() > 30) {
                        descriptionEditText.setError("Location must be max 30 characters.");
                    }
                }
            }
        } else {
            showCustomToast.showToast(UploadVideoActivity.this, "Please check your internet connection.");
        }
    } else if (v.getId() == isAssignmentButton.getId()) {
        if (isAssignment.equalsIgnoreCase("NO")) {
            isAssignment = "YES";
            isAssignmentButton.setText("YES");
        } else {
            isAssignment = "NO";
            isAssignmentButton.setText("NO");
        }
    } else if (v.getId() == wallRelativeLayout.getId()) {
        Intent i = new Intent(UploadVideoActivity.this, WallActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(i);
        finish();
    } else if (v.getId() == settingsRelativeLayout.getId()) {
        Intent i = new Intent(UploadVideoActivity.this, SettingsActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(i);
        finish();
    } else if (v.getId() == okButton.getId()) {
        //go to settings page to enable GPS
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, REQUEST_CODE);
        locationDialog.dismiss();
    } else if (v.getId() == cancelButton.getId()) {
        locationDialog.dismiss();
    }

}

From source file:samples.piggate.com.piggateCompleteExample.Activity_Logged.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    _piggate = new Piggate(this, null); //Initialize the Piggate object
    setContentView(R.layout.activity_logged);
    getSupportActionBar().setTitle(PiggateUser.getEmail());

    startService(new Intent(getApplicationContext(), Service_Notify.class)); //Start the service

    //Initialize and set all the left navigation drawer fields
    mDrawer = new Drawer().withActivity(this).withTranslucentStatusBar(false).withHeader(R.layout.drawerheader)
            .addDrawerItems( /* Add drawer items with this method */)
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override//  www.j  a va 2 s  .co  m
                public void onItemClick(AdapterView<?> parent, View view, int position, long id,
                        IDrawerItem drawerItem) {
                    // Open the exchange activity for the selected item
                    Intent slideactivity = new Intent(Activity_Logged.this, Activity_Exchange.class);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                    //Send the current offer information to the exchange activity
                    slideactivity.putExtra("offerName", exchangeOfferList.get(position).getName().toString());
                    slideactivity.putExtra("offerDescription",
                            exchangeOfferList.get(position).getDescription().toString());
                    slideactivity.putExtra("offerImgURL",
                            exchangeOfferList.get(position).getImgURL().toString());
                    slideactivity.putExtra("exchangeID",
                            exchangeOfferList.get(position).getExchangeID().toString());

                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(Activity_Logged.this,
                            R.anim.slidefromright, R.anim.slidetoleft).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }
            }).withSliderBackgroundColor(Color.parseColor("#FFFFFF")).withSelectedItem(-1).build();

    //Initialize recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(Activity_Logged.this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    newBeaconsLayout = (LinearLayout) findViewById(R.id.newBeaconsLayout);

    //Initialize swipe layout
    mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    mSwipeLayout.setOnRefreshListener(this);

    errorDialog = new AlertDialog.Builder(this).create();
    errorDialog.setTitle("Logout error");
    errorDialog.setMessage("There is an error with the logout");
    errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    successPaymentDialog = new AlertDialog.Builder(this).create();
    successPaymentDialog.setTitle("Successful payment");
    successPaymentDialog.setMessage("Now you can exchange your purchased product");
    successPaymentDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    errorBuyDialog = new AlertDialog.Builder(this).create();
    errorBuyDialog.setTitle("Payment failed");
    errorBuyDialog.setMessage("There is an error with your payment");
    errorBuyDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    successExchangeDialog = new AlertDialog.Builder(this).create();
    successExchangeDialog.setTitle("Offer successfully exchanged");
    successExchangeDialog.setMessage("The offer has been purchased and exchanged");
    successExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    errorExchangeDialog = new AlertDialog.Builder(this).create();
    errorExchangeDialog.setTitle("Exchange error");
    errorExchangeDialog.setMessage("There is an error with the exchange");
    errorExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    networkErrorDialog = new AlertDialog.Builder(this).create();
    networkErrorDialog.setTitle("Network error");
    networkErrorDialog.setMessage("There is an error with the network connection");
    networkErrorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    fadeIn = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadein);
    fadeOut = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadeout);

    //Check if the bluetooth is switched on
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    if (getIntent().hasExtra("payment")) {
        if (getIntent().getExtras().getBoolean("payment") == true) {
            successPaymentDialog.show(); //Show success payment dialog
            mDrawer.openDrawer(); //Open the left panel
        } else {
            errorBuyDialog.show(); //Show payment error dialog
        }
    } else if (getIntent().hasExtra("exchanged")) {
        if (getIntent().getExtras().getBoolean("exchanged") == true) {
            successExchangeDialog.show(); //Show exchange success dialog
        } else {
            errorExchangeDialog.show(); //Show exchange error dialog
        }
    }
}

From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * //from w ww. j a  va 2s .c o  m
 * @param url
 *          The url to load.
 * @param usePhoneGap
 *          Load url in PhoneGap webview
 * @return "" if ok, or error message.
 */
public String openExternal(String urlToOpen, String encodedCredentials) {
    try {
        // set the download URL, a url that points to a file on the internet
        // this is the file to be downloaded
        URL url = new URL(urlToOpen);

        // create the new connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // set up some things on the connection
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        urlConnection.setRequestProperty("Authorization", encodedCredentials);

        // and connect!
        urlConnection.connect();

        // set the path where we want to save the file
        // in this case, going to save it on the root directory of the
        // sd card.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        // create a new file, specifying the path, and the filename
        // which we want to save the file as.
        File file = new File(SDCardRoot, "temp.pdf");

        // this will be used to write the downloaded data into the file we created
        FileOutputStream fileOutput = new FileOutputStream(file);

        // this will be used in reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        // this is the total size of the file
        int totalSize = urlConnection.getContentLength();
        // variable to store total downloaded bytes
        int downloadedSize = 0;

        // create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0; // used to store a temporary size of the buffer

        // now, read through the input buffer and write the contents to the file
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            // add the data in the buffer to the file in the file output stream (the
            // file on the sd card
            fileOutput.write(buffer, 0, bufferLength);
            // add up the size so we know how much is downloaded
            downloadedSize += bufferLength;

        }
        // close the output stream when done
        fileOutput.close();

        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.cordova.getActivity().startActivity(intent);

        // catch some possible errors...
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";

}

From source file:com.playhaven.android.view.HTMLView.java

/**
 * This switches on the host portion of a request prefixed with
 * DISPATCH_PREFIX in order to handle events from the content templates.
 *
 * @TODO this would be a good candidate for factoring out to a cleaner custom WebViewClient
 *
 * @param dispatchUrl/*from  w  ww  . ja  v  a2 s. co  m*/
 */
private void handleDispatch(String dispatchUrl) {
    Uri callbackUri = Uri.parse(dispatchUrl);
    String callbackId = callbackUri.getQueryParameter("callback");
    String callbackString = callbackUri.getHost();
    String dispatchContext = callbackUri.getQueryParameter("context");
    PlayHaven.d("Handling dispatch: %s of type %s", dispatchUrl, callbackString);

    switch (Dispatches.valueOf(callbackString)) {
    /**
     * closeButton hides the native emergency close button, and passes
     * notice of whether it was hidden back to the content template
     */
    case closeButton:
        String hidden = "true";
        try {
            hidden = new JSONObject(dispatchContext).getString("hidden");
        } catch (JSONException jse) {
            // Default to NOT hiding the emergency close button
            hidden = "false";
        }

        if ("true".equals(hidden)) {
            ((PlayHavenView) getParent()).setExitVisible(false);
        }

        // Tell the content template that we've hidden the emergency close button.
        this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, "{'hidden':'" + hidden + "'}", null));
        break;
    /**
     * dismiss triggers the contentDismissed listener
     */
    case dismiss:
        PlayHavenView.DismissType dismiss = PlayHavenView.DismissType.NoThanks;
        if (mRewards != null)
            dismiss = PlayHavenView.DismissType.Reward;

        if (mDataFields != null)
            dismiss = PlayHavenView.DismissType.OptIn;

        if (mPurchases != null)
            dismiss = PlayHavenView.DismissType.Purchase;

        mPlacement.getListener().contentDismissed(mPlacement, dismiss, generateResponseBundle());

        // Unregister the web view client so that any future dispatches will be ignored.
        HTMLView.this.setWebViewClient(null);

        break;
    /**
     * launch retrieves a URL from the server to be parsed using
     * Intent.ACTION_VIEW
     */
    case launch:
        mPlacement.getListener().contentDismissed(mPlacement, PlayHavenView.DismissType.Launch, null);

        /*
         * We can't get this from the original model because we don't
         * know which one they picked (if this was a more_games template).
         */
        String url;
        try {
            url = new JSONObject(dispatchContext).getString("url");
        } catch (JSONException jse) {
            PlayHaven.e("Could not parse launch URL.");
            return;
        }

        UrlRequest urlRequest = new UrlRequest(url);
        ExecutorService pool = Executors.newSingleThreadExecutor();
        final Future<String> uriFuture = pool.submit(urlRequest);
        final String initialUrl = url;

        new Thread(new Runnable() {
            @Override
            public void run() {
                // Wait for our final link.
                String url = null;
                try {
                    url = uriFuture.get();
                } catch (Exception e) {
                    PlayHaven.v("Could not retrieve launch URL from server. Using initial url.");

                    // If the redirect failed, proceed with the original url.
                    url = initialUrl;
                }

                // Launch whatever it is. It might be a Play, web, or other link
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    HTMLView.this.getContext().startActivity(intent);
                } catch (Exception e) {
                    PlayHaven.e("Unable to launch URI from template.");
                    e.printStackTrace();
                }
            }
        }).start();
        break;
    /**
     * loadContext passes the full "context" JSON blob to the
     * content template
     */
    case loadContext:
        this.loadUrl(DISPATCH_PROTOCOL_TEMPLATE);
        net.minidev.json.JSONObject context = JsonUtil.getPath(mPlacement.getModel(), "$.response.context");

        /**
         * @playhaven.apihack KitKat+ changed how the webview is loaded
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.evaluateJavascript(String.format(CALLBACK_TEMPLATE, callbackId, context, null), null);
        } else {
            this.loadUrl(String.format(CALLBACK_TEMPLATE, callbackId, context, null));
        }
        break;
    /**
     * purchase stores the purchase object (which is generated by the
     * content template) as mPurchases, for use with dismiss dispatch
     */
    case purchase:
        collectAttachments(dispatchContext);
        break;
    /**
     * reward stores the reward object (which is generated by the
     * content template) as mRewards, for use with dismiss dispatch
     */
    case reward:
        net.minidev.json.JSONObject rewardParam = JsonUtil.getPath(mPlacement.getModel(),
                "$.response.context.content.open_dispatch.parameters");
        if (rewardParam == null || rewardParam.size() == 0) {
            // data_collection template sends a reward dispatch when it submits form data ...
            // @TODO: have templates return more than key/value pairs (eg class, pattern)
            this.loadUrl(COLLECT_FORM_DATA);
        }

        collectAttachments(dispatchContext);
        break;
    /**
     * subcontent takes a JSON blob generated by the content template
     * and uses that to get data for a new impression, currently a
     * more_games widget that follows a featured ad
     */
    case subcontent:
        SubcontentRequest subcontentRequest = new SubcontentRequest(dispatchContext);
        subcontentRequest.send(getContext());
        break;
    /**  @TODO Find out why this dispatch was abandoned in 1.12 */
    case track:
        PlayHaven.d("track callback not implemented.");
        break;
    /**
     * This is one injected to let the Android SDK harvest data from the
     * opt-in data collection form.
     */
    case dcData:
        try {
            mDataFields = DataCollectionField.fromUrl(callbackUri);
        } catch (PlayHavenException e) {
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}