Example usage for android.content Intent FLAG_ACTIVITY_NEW_TASK

List of usage examples for android.content Intent FLAG_ACTIVITY_NEW_TASK

Introduction

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

Prototype

int FLAG_ACTIVITY_NEW_TASK

To view the source code for android.content Intent FLAG_ACTIVITY_NEW_TASK.

Click Source Link

Document

If set, this activity will become the start of a new task on this history stack.

Usage

From source file:com.almarsoft.GroundhogReader.MessageActivity.java

protected void attachClicked(final String attachcode) {

    HashMap<String, String> tmpattachPart = null;
    String tmpmd5 = null;//w  ww. ja va 2 s.c  om

    for (HashMap<String, String> part : mMimePartsVector) {
        tmpmd5 = part.get("md5");
        if (tmpmd5.equals(attachcode)) {
            tmpattachPart = part;
            break;
        }
    }

    final String md5 = tmpmd5;
    final HashMap<String, String> attachPart = tmpattachPart;

    if (attachPart != null && md5 != null) {

        new AlertDialog.Builder(this).setTitle(getString(R.string.attachment))
                .setMessage(getString(R.string.open_save_attach_question))
                .setPositiveButton(getString(R.string.open), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(android.content.Intent.ACTION_VIEW);
                        File attFile = new File(UsenetConstants.EXTERNALSTORAGE + "/" + UsenetConstants.APPNAME
                                + "/" + UsenetConstants.ATTACHMENTSDIR + "/" + mGroup, md5);
                        Uri attachUri = Uri.fromFile(attFile);
                        intent.setDataAndType(attachUri, attachPart.get("type"));
                        startActivity(intent);
                    }
                }).setNegativeButton(getString(R.string.save), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        try {
                            String finalPath = FSUtils.saveAttachment(md5, mGroup, attachPart.get("name"));
                            Toast.makeText(MessageActivity.this, getString(R.string.saved_to) + finalPath,
                                    Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(MessageActivity.this,
                                    getString(R.string.could_not_save_colon) + e.toString(), Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }).show();
    }
}

From source file:com.dnielfe.manager.utils.SimpleUtils.java

public static void createShortcut(Activity main, String path) {
    File file = new File(path);

    try {//from   ww  w .  j  av a  2s .  c  o  m
        // Create the intent that will handle the shortcut
        Intent shortcutIntent = new Intent(main, Browser.class);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        shortcutIntent.putExtra(Browser.EXTRA_SHORTCUT, path);

        // The intent to send to broadcast for register the shortcut intent
        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, file.getName());
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(main, R.drawable.ic_launcher));
        intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        main.sendBroadcast(intent);

        Toast.makeText(main, main.getString(R.string.shortcutcreated), Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(main, main.getString(R.string.error), Toast.LENGTH_SHORT).show();
    }
}

From source file:com.farmerbb.secondscreen.util.U.java

public static String uiRefreshCommand2(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    // For better reliability, we execute the UI refresh while on the home screen
    Intent homeIntent = new Intent(Intent.ACTION_MAIN);
    homeIntent.addCategory(Intent.CATEGORY_HOME);
    homeIntent.addCategory(Intent.CATEGORY_DEFAULT);
    homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(homeIntent);//from  w  w w .  j  a v a2  s  .c o  m

    // Kill all background processes, in order to fully refresh UI
    PackageManager pm = context.getPackageManager();
    List<ApplicationInfo> packages = pm.getInstalledApplications(0);
    for (ApplicationInfo packageInfo : packages) {
        if (!packageInfo.packageName.equalsIgnoreCase(context.getPackageName()))
            am.killBackgroundProcesses(packageInfo.packageName);
    }

    // Get launcher package name
    final ResolveInfo mInfo = pm.resolveActivity(homeIntent, 0);

    return "sleep 1 && am force-stop " + mInfo.activityInfo.applicationInfo.packageName;
}

From source file:com.bt.download.android.gui.util.UIUtils.java

/**
 * Opens the given file with the default Android activity for that File and
 * mime type.//from   www.  j a  v a 2  s  . c om
 * 
 * @param filePath
 * @param mime
 */
public static void openFile(Context context, String filePath, String mime) {
    try {
        if (!openAudioInternal(filePath)) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.fromFile(new File(filePath)), mime);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);

            if (mime != null && mime.contains("video")) {
                if (MusicUtils.isPlaying()) {
                    MusicUtils.playOrPause();
                }
                UXStats.instance().log(UXAction.LIBRARY_VIDEO_PLAY);
            }
        }
    } catch (Throwable e) {
        UIUtils.showShortMessage(context, R.string.cant_open_file);
        Log.e(TAG, "Failed to open file: " + filePath, e);
    }
}

From source file:com.groupme.sdk.GroupMeConnect.java

/**
 * Opens the Android Market to download the GroupMe application.
 *
 * @since 1/* w  w w . j  a va 2s.c om*/
 */
public void downloadGroupMeApp() {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setData(Uri.parse("market://details?id=com.groupme.android"));

    mContext.startActivity(intent);
}

From source file:com.couchbase.touchdb.testapp.tests.HeavyAttachments.java

/**
 * Helper function to attach (many) images to a document to test heavy docs
 * with large attachments or multiple attachments
 * /*  w ww . j  a v  a2s  . co  m*/
 * 
 * @param howMany
 *          how many images we want to add (default is two or more)
 * @param startingRev
 *          The TDRevision we want to add to
 */
public TDRevision attachImages(int howMany, TDRevision startingRev) {
    /*
     * Add two or more image attachments to the documents, these attachments are
     * copied by the CopySampleAttachmentsActivity.
     */
    Intent copyImages = new Intent(getInstrumentation().getContext(), CopySampleAttachmentsActivity.class);
    copyImages.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getInstrumentation().startActivitySync(copyImages);

    // Attach sample images to doc2
    FileInputStream fileStream = null;
    FileInputStream fileStream2 = null;
    boolean sampleFilesExistAndWereCopied = true;
    try {
        fileStream = new FileInputStream(
                "/data/data/com.couchbase.touchdb.testapp/files/sample_attachment_image1.jpg");
        byte[] imageAttachment = IOUtils.toByteArray(fileStream);
        if (imageAttachment.length == 0) {
            sampleFilesExistAndWereCopied = false;
        }
        TDStatus status = database.insertAttachmentForSequenceWithNameAndType(
                new ByteArrayInputStream(imageAttachment), startingRev.getSequence(),
                "sample_attachment_image1.jpg", "image/jpeg", startingRev.getGeneration());
        Assert.assertEquals(TDStatus.CREATED, status.getCode());

        fileStream2 = new FileInputStream(
                "/data/data/com.couchbase.touchdb.testapp/files/sample_attachment_image2.jpg");
        byte[] secondImageAttachment = IOUtils.toByteArray(fileStream2);
        if (secondImageAttachment.length == 0) {
            sampleFilesExistAndWereCopied = false;
        }
        status = database.insertAttachmentForSequenceWithNameAndType(
                new ByteArrayInputStream(secondImageAttachment), startingRev.getSequence(),
                "sample_attachment_image2.jpg", "image/jpeg", startingRev.getGeneration());
        Assert.assertEquals(TDStatus.CREATED, status.getCode());

        int howManyMoreToAdd = howMany - 2;
        if (howManyMoreToAdd < 1) {
            howManyMoreToAdd = 0;
        }
        for (int i = 0; i < howManyMoreToAdd; i++) {
            status = database.insertAttachmentForSequenceWithNameAndType(
                    new ByteArrayInputStream(secondImageAttachment), startingRev.getSequence(),
                    "sample_attachment_image_test_out_of_memory" + i + ".jpg", "image/jpeg",
                    startingRev.getGeneration());
            Assert.assertEquals(TDStatus.CREATED, status.getCode());
            int imagesSoFar = i + 2;
            Log.d(TAG, "Attached " + imagesSoFar + "images.");
            if (status.getCode() != TDStatus.CREATED) {
                break;
            }
        }

    } catch (FileNotFoundException e) {
        sampleFilesExistAndWereCopied = false;
        e.printStackTrace();
    } catch (IOException e) {
        sampleFilesExistAndWereCopied = false;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fileStream);
        IOUtils.closeQuietly(fileStream2);
    }
    if (!sampleFilesExistAndWereCopied) {
        Log.e(TAG,
                "The sample image files for testing multipart attachment upload weren't copied to the SDCARD, ");
    }
    Assert.assertTrue(sampleFilesExistAndWereCopied);
    return startingRev;
}

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   ww w  .  j  a v  a  2s  .  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;
    }
}

From source file:RhodesService.java

public static void runApplication(String appName, Object params) {
    try {/*from   w w w.  ja v  a  2  s.  c o m*/
        Context ctx = RhodesService.getContext();
        PackageManager mgr = ctx.getPackageManager();
        PackageInfo info = mgr.getPackageInfo(appName, PackageManager.GET_ACTIVITIES);
        if (info.activities.length == 0) {
            Logger.E(TAG, "No activities found for application " + appName);
            return;
        }
        ActivityInfo ainfo = info.activities[0];
        String className = ainfo.name;
        if (className.startsWith("."))
            className = ainfo.packageName + className;

        Intent intent = new Intent();
        intent.setClassName(appName, className);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (params != null) {
            Bundle startParams = new Bundle();
            if (params instanceof String) {
                if (((String) params).length() != 0) {
                    String[] paramStrings = ((String) params).split("&");
                    for (int i = 0; i < paramStrings.length; ++i) {
                        String key = paramStrings[i];
                        String value = "";
                        int splitIdx = key.indexOf('=');
                        if (splitIdx != -1) {
                            value = key.substring(splitIdx + 1);
                            key = key.substring(0, splitIdx);
                        }
                        startParams.putString(key, value);
                    }
                }
            } else
                throw new IllegalArgumentException("Unknown type of incoming parameter");

            intent.putExtras(startParams);
        }
        ctx.startActivity(intent);
    } catch (Exception e) {
        Logger.E(TAG, "Can't run application " + appName + ": " + e.getMessage());
    }
}