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.example.sabeeh.helloworld.AuthService.java

/**
 * Handles logging the user out including:
 * -deleting cookies so their login with a provider won't be cached in the web view
 * -removing the userdata from the shared preferences
 * -setting the current user object on the client to logged out
 * -optionally redirects to the login page if requested
 * @param shouldRedirectToLogin/*from   w ww  .j  av  a  2s .  c o m*/
 */
public void logout(boolean shouldRedirectToLogin) {
    //Clear the cookies so they won't auto login to a provider again
    CookieSyncManager.createInstance(mContext);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    //Clear the user id and token from the shared preferences
    ClearcacheUserToken();
    //Clear the user and return to the auth activity
    mClient.logout();
    //Take the user back to the auth activity to relogin if requested
    if (shouldRedirectToLogin) {
        Intent logoutIntent = new Intent(mContext, LoginActivity.class);
        logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(logoutIntent);
    }
}

From source file:it.telecomitalia.my.base_struct_apps.VersionUpdate.java

@Override
protected Void doInBackground(String... urls) {
    /* metodo principale per aggiornamento */
    String xml = "";
    try {/*from  ww w . j av  a2s.co m*/
        /* tento di leggermi il file XML remoto */
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(SERVER + PATH + VERSIONFILE);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
        /* ora in xml c' il codice della pagina degli aggiornamenti */
    } catch (IOException e) {
        e.printStackTrace();
    }
    // TODO: org.apache.http.conn.HttpHostConnectException ovvero host non raggiungibile
    try {
        /* nella variabile xml, c' il codice della pagina remota per gli aggiornamenti.
        * Per le mie esigenze, prendo dall'xml l'attributo value per vedere a che versione  la
        * applicazione sul server.*/
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // http://stackoverflow.com/questions/1706493/java-net-malformedurlexception-no-protocol
        InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Document dom = db.parse(is);
        Element element = dom.getDocumentElement();
        Element current = (Element) element.getElementsByTagName("current").item(0);
        currentVersion = current.getAttribute("value");
        currentApkName = current.getAttribute("apk");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* con il costruttore ho stabilito quale versione sta girando sul terminale, e con questi
    * due try, mi son letto XML remoto e preso la versione disponibile sul server e il relativo
    * nome dell'apk, caso ai dovesse servirmi. Ora li confronto e decido che fare */
    if (currentVersion != null & runningVersion != null) {
        /* esistono, li trasformo in double */
        Double serverVersion = Double.parseDouble(currentVersion);
        Double localVersion = Double.parseDouble(runningVersion);
        /* La versione server  superiore alla mia ! Occorre aggiornare */
        if (serverVersion > localVersion) {
            try {
                /* connessione al server */
                URL urlAPK = new URL(SERVER + PATH + currentApkName);
                HttpURLConnection con = (HttpURLConnection) urlAPK.openConnection();
                con.setRequestMethod("GET");
                con.setDoOutput(true);
                con.connect();
                // qual' la tua directory di sistema Download ?
                File downloadPath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                File outputFile = new File(downloadPath, currentApkName);
                //Log.i("test", downloadPath.getAbsolutePath());
                //Log.i("test", outputFile.getAbsolutePath());
                // se esistono download parziali o vecchi, li elimino.
                if (outputFile.exists())
                    outputFile.delete();
                /* mi creo due File Stream uno di input, quello che sto scaricando dal server,
                * e l'altro di output, quello che sto creando nella directory Download*/
                InputStream input = con.getInputStream();
                FileOutputStream output = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.close();
                input.close();
                /* una volta terminato il processo, attraverso un intent lancio il file che ho
                * appena scaricato in modo da installare immediatamente l'aggiornamento come
                * specificato qui
                * http://stackoverflow.com/questions/4967669/android-install-apk-programmatically*/
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(outputFile.getAbsolutePath())),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:org.wso2.app.catalog.api.ApplicationManager.java

/**
 * Removes an application from the device.
 *
 * @param packageName - Application package name should be passed in as a String.
 *//*from  w ww  . j  a va2s  .  c om*/
public void uninstallApplication(String packageName) {
    if (packageName != null
            && !packageName.contains(resources.getString(R.string.application_package_prefix))) {
        packageName = resources.getString(R.string.application_package_prefix) + packageName;
    }

    if (isPackageInstalled(Constants.AGENT_PACKAGE_NAME)) {
        CommonUtils.callAgentApp(context, Constants.Operation.UNINSTALL_APPLICATION, packageName, null);
    } else {
        Uri packageURI = Uri.parse(packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        uninstallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(uninstallIntent);
    }
}

From source file:me.piebridge.prevent.ui.UserGuideActivity.java

private boolean donateViaWeChat() {
    File qrCode = getQrCode();//from  w w w  .  j  a va2  s. c om
    if (qrCode == null) {
        return false;
    }
    try {
        FileUtils.dumpFile(getAssets().open("wechat.png"), qrCode);
    } catch (IOException e) {
        UILog.d("cannot dump wechat", e);
        return false;
    }
    refreshQrCode(qrCode);
    showDonateDialog();
    Intent intent = new Intent("com.tencent.mm.action.BIZSHORTCUT");
    intent.setPackage("com.tencent.mm");
    intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    try {
        startActivity(intent);
        for (int i = 0; i < 0x3; ++i) {
            Toast.makeText(this, R.string.select_qr_code, Toast.LENGTH_LONG).show();
        }
    } catch (Throwable t) { // NOSONAR
        hideDonateDialog();
    }
    return true;
}

From source file:com.android.prachat.gcm.MyGcmPushReceiver.java

/**
 * Showing notification with text only//from   w w  w .ja  v  a2  s. c  o m
 * */
private void showNotificationMessage(Context context, String title, String message, String timeStamp,
        Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

From source file:de.da_sense.moses.client.abstraction.ApkMethods.java

/**
 * Installs a given APK file.//from  ww  w .ja  v a2  s.  c o  m
 * 
 * @param apk
 *            the apk file to install
 * @param baseActivity
 *            the base activity
 * @throws IOException
 *             if the file does not exist
 */
public static void installApk(File apk, ExternalApplication appRef, ApkInstallObserver o) throws IOException {
    MosesService service = MosesService.getInstance();
    if (service != null) {
        if (apk.exists()) {
            InstallApkActivity.setAppToInstall(apk, appRef, o);
            Intent installActivityIntent = new Intent(service, InstallApkActivity.class);
            installActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            service.startActivity(installActivityIntent);
        } else {
            o.apkInstallError(apk, appRef,
                    new RuntimeException("Could not install apk file because it was nonexistent."));
        }
    } else {
        o.apkInstallError(apk, appRef,
                new RuntimeException("Could not install apk file because the service was not running."));
    }
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

public static boolean isUpdateAvailable() {
    boolean exitForError = true;
    String localVersion = System.getAppVersionName();

    // cannot retrieve installed apk version
    if (localVersion == null)
        return false;

    try {// w  w w  .  j av a 2s. c  o m
        synchronized (mApkInfo) {
            // Read remote version
            if (mApkInfo.version == null) {
                URL url = new URL(REMOTE_VERSION_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line, buffer = "";

                while ((line = reader.readLine()) != null) {
                    buffer += line + "\n";
                }

                reader.close();
                mApkInfo.url = REMOTE_APK_URL;
                mApkInfo.versionString = buffer.split("\n")[0].trim();
                if (!VERSION_CHECK.matcher(mApkInfo.versionString).matches())
                    throw new org.apache.http.ParseException(
                            String.format("remote version parse failed: '%s'", mApkInfo.versionString));
                mApkInfo.version = getVersionCode(mApkInfo.versionString);
                mApkInfo.name = String.format("dSploit-%s.apk", mApkInfo.versionString);
                mApkInfo.path = String.format("%s/%s", System.getStoragePath(), mApkInfo.name);
                mApkInfo.contentIntent = new Intent(Intent.ACTION_VIEW);
                mApkInfo.contentIntent.setDataAndType(Uri.fromFile(new File(mApkInfo.path)),
                        "application/vnd.android.package-archive");
                mApkInfo.contentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }

            // Compare versions
            double installedVersionCode = getVersionCode(localVersion);

            Logger.debug(
                    String.format("mApkInstalledVersion = %s ( %s ) ", localVersion, installedVersionCode));
            Logger.debug(String.format("mRemoteVersion       = %s ( %s ) ", mApkInfo.versionString,
                    mApkInfo.version));

            exitForError = false;

            if (mApkInfo.version > installedVersionCode)
                return true;
        }
    } catch (org.apache.http.ParseException e) {
        Logger.error(e.getMessage());
    } catch (Exception e) {
        System.errorLogging(e);
    } finally {
        if (exitForError)
            mApkInfo.reset();
    }

    return false;
}

From source file:com.VVTeam.ManHood.Fragment.HistogramFragment.java

private void initViews(View view) {
    parentLayout = (RelativeLayout) view.findViewById(R.id.fragment_histogram_parent_relative_layout);
    /*BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;//from   ww  w.  j ava  2  s .co m
    parentLayout.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.histogram_bg, options)));*/
    settingsRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_settings_relative_layout);
    markRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_mark_relative_layout);
    worldRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_world_relative);
    //        worldRelative.setSelected(true);
    worldRelative.setBackgroundResource(R.drawable.cell_p);
    areaRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_area_relative);
    hoodRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_hood_relative);
    yourResultButton = (Button) view.findViewById(R.id.fragment_histogram_your_result_button);

    contentRelative = (RelativeLayout) view.findViewById(R.id.fragment_histogram_content_relative);

    RelativeLayout shareRelative = (RelativeLayout) view
            .findViewById(R.id.fragment_histogram_share_button_relative);
    shareRelative.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            GoogleTracker.StarSendEvent(getActivity(), "ui_action", "user_action", "histogram_share");

            Bitmap image = makeSnapshot();

            File pictureFile = getOutputMediaFile();
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                image.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.close();

            } catch (Exception e) {

            }

            //            String pathofBmp = Images.Media.insertImage(getActivity().getContentResolver(), makeSnapshot(), "Man Hood App", null);
            //             Uri bmpUri = Uri.parse(pathofBmp);
            Uri bmpUri = Uri.fromFile(pictureFile);
            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            emailIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            emailIntent.setType("image/png");
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Man Hood App");
            getActivity().startActivity(emailIntent);

        }
    });

    polarPlot = (PolarPlot) view.findViewById(R.id.polarPlot);

    thicknessHisto = (Histogram) view.findViewById(R.id.thicknessHisto);
    thicknessHisto.setOrientation(ORIENT.LEFT);
    thicknessHisto.setBackgroundColor(Color.TRANSPARENT);
    lengthHisto = (Histogram) view.findViewById(R.id.lengthHistogram);
    lengthHisto.setOrientation(ORIENT.RIGHT);
    lengthHisto.setBackgroundColor(Color.TRANSPARENT);
    girthHisto = (Histogram) view.findViewById(R.id.girthHistogram);
    girthHisto.setOrientation(ORIENT.BOTTOM);
    girthHisto.setBackgroundColor(Color.TRANSPARENT);

    lengthHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestLength(value));

                setSelection(true, girthHisto, usersData.girthOfUserWithID(nearestUserID));
                setSelection(true, thicknessHisto, usersData.thicknessOfUserWithID(nearestUserID));
                //               setSelection(false, lengthHisto, 0.0f);
                setSelection(true, lengthHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);
                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    girthHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestGirth(value));

                setSelection(true, lengthHisto, usersData.lengthOfUserWithID(nearestUserID));
                setSelection(true, thicknessHisto, usersData.thicknessOfUserWithID(nearestUserID));
                //               setSelection(false, girthHisto, 0.0f);
                setSelection(true, girthHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);

                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    thicknessHisto.setCallBackListener(new HistogramCallBack() {

        @Override
        public void setValueSelectionChangedBlock(Histogram histo, HistogramSelectionState selectionState,
                float value, HistogramBin bin) {
            // TODO Auto-generated method stub
            if (selectionState == HistogramSelectionState.HistogramSelectionStateSelected) {
                histogramSelected = true;

                setNearestUserID(usersData.userIDWithNearestThickness(value));

                setSelection(true, girthHisto, usersData.girthOfUserWithID(nearestUserID));
                setSelection(true, lengthHisto, usersData.lengthOfUserWithID(nearestUserID));
                //                 setSelection(false, thicknessHisto, 0.0f);
                setSelection(true, thicknessHisto, value);

                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateNotSelected) {
                histogramSelected = false;

                setNearestUserID(null);
                setSelectionForAverage();
                setupPolarPlotWithCurrentUserID(nearestUserID, usersData, selfUserData);
            } else if (selectionState == HistogramSelectionState.HistogramSelectionStateDelayedFinish) {

            }

        }
    });

    textBoxTitleLabel = (TextView) view.findViewById(R.id.txtBoxTitle);
    textBoxTitleLabel.setText("AVERAGE");

    layoutSubTitle = (LinearLayout) view.findViewById(R.id.layoutSubTitle);
    layoutSubTitle.setVisibility(View.INVISIBLE);
    textBoxSubtitleLabel = (TextView) view.findViewById(R.id.txtBoxSubTitleLabel);
    textBoxSubtitleValueLabel = (TextView) view.findViewById(R.id.txtBoxSubTitleValue);

    lengthSelectedLabel = (TextView) view.findViewById(R.id.txtlengthselected);
    lengthSelectedLabel.setText("50%");
    lengthTOPLabel = (TextView) view.findViewById(R.id.lengthTOPLabel);

    girthSelectedLabel = (TextView) view.findViewById(R.id.txtgirthselected);
    girthSelectedLabel.setText("50%");
    girthTOPLabel = (TextView) view.findViewById(R.id.girthTOPLabel);

    thicknessSelectedLabel = (TextView) view.findViewById(R.id.txtthicknessselected);
    thicknessSelectedLabel.setText("50%");
    thinkestAtTOPLabel = (TextView) view.findViewById(R.id.thinkestAtTOPLabel);

    curvedSelectedLabel = (TextView) view.findViewById(R.id.txtcurvedselected);
    curvedSelectedLabel.setText("0");

    girthTopLB = (TextView) view.findViewById(R.id.girthTop);
    girthMiddleLB = (TextView) view.findViewById(R.id.girthMiddle);
    girthBottomLB = (TextView) view.findViewById(R.id.girthBottom);

    thicknessTopLB = (TextView) view.findViewById(R.id.thicknessTop);
    thicknessMiddleLB = (TextView) view.findViewById(R.id.thicknessMiddle);
    thicknessBottomLB = (TextView) view.findViewById(R.id.thicknessBottom);

    lengthTopLB = (TextView) view.findViewById(R.id.lengthTop);
    lengthMiddleLB = (TextView) view.findViewById(R.id.lengthMiddle);
    lengthBottomLB = (TextView) view.findViewById(R.id.lengthBottom);

    settingsRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).openSettingsActivity();
        }
    });
    markRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((MainActivity) getActivity()).openCertificateActivity();
        }
    });

    worldRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRangeAll);
            updateRangeSwitch();
        }
    });
    areaRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRange200);
            updateRangeSwitch();
        }
    });
    hoodRelative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelectedRange(SliceRange.SliceRange20);
            updateRangeSwitch();
        }
    });

    yourResultButton.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                youTouchDown();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                youTouchUp();
                //               final Handler handler = new Handler();
                //                handler.postDelayed(new Runnable() {
                //                    @Override
                //                    public void run() {
                //                       youTouchUp();             
                //                    }
                //                }, 2000);
            }

            return true;
        }
    });

    RequestManager.getInstance().checkUser();

    /* in-app billing */
    String base64EncodedPublicKey = LICENSE_KEY;

    // Create the helper, passing it our context and the public key to verify signatures with
    Log.d(TAG, "Creating IAB helper.");
    mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);

    // enable debug logging (for a production application, you should set this to false).
    mHelper.enableDebugLogging(true);

    // Start setup. This is asynchronous and the specified listener
    // will be called once setup completes.
    Log.d(TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            Log.d(TAG, "Setup finished.");

            if (!result.isSuccess()) {
                // Oh noes, there was a problem.
                Log.d(TAG, "Problem setting up in-app billing: " + result);
                return;
            }

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null)
                return;

            // IAB is fully set up. Now, let's get an inventory of stuff we own.
            Log.d(TAG, "Setup successful. Querying inventory.");
            mHelper.queryInventoryAsync(mGotInventoryListener);
        }
    });

}

From source file:com.jaspersoft.android.jaspermobile.test.acceptance.favorites.FavoritesPageTest.java

private void startContextMenuInteractionTest() throws InterruptedException {
    FakeHttpLayerManager.addHttpResponseRule(ApiMatcher.INPUT_CONTROLS, TestResponses.get().noContent());
    FakeHttpLayerManager.addHttpResponseRule(ApiMatcher.REPORT_EXECUTIONS, TestResponses.get().noContent());

    Intent intent = LibraryActivity_.intent(mApplication).flags(Intent.FLAG_ACTIVITY_NEW_TASK).get();
    getInstrumentation().startActivitySync(intent);
    getInstrumentation().waitForIdleSync();

    onData(is(instanceOf(ResourceLookup.class))).inAdapterView(withId(android.R.id.list)).atPosition(0)
            .perform(longClick());//from  www  .  j  a v  a 2 s  .  c o m
    onView(withId(R.id.favoriteAction)).perform(click());
    pressBack();
    pressBack();

    onData(is(instanceOf(Cursor.class))).inAdapterView(withId(android.R.id.list)).atPosition(0)
            .perform(click());
    pressBack();

    intent = LibraryActivity_.intent(mApplication).flags(Intent.FLAG_ACTIVITY_NEW_TASK).get();
    getInstrumentation().startActivitySync(intent);
    getInstrumentation().waitForIdleSync();

    onData(is(instanceOf(ResourceLookup.class))).inAdapterView(withId(android.R.id.list)).atPosition(0)
            .perform(longClick());
    onView(withId(R.id.favoriteAction)).perform(click());
    pressBack();
    pressBack();

    Thread.sleep(200);
    onView(withId(android.R.id.list)).check(hasTotalCount(0));
    onView(withId(android.R.id.empty))
            .check(matches(allOf(withText(R.string.f_empty_list_msg), isDisplayed())));

    intent = LibraryActivity_.intent(mApplication).flags(Intent.FLAG_ACTIVITY_NEW_TASK).get();
    getInstrumentation().startActivitySync(intent);
    getInstrumentation().waitForIdleSync();

    onData(is(instanceOf(ResourceLookup.class))).inAdapterView(withId(android.R.id.list)).atPosition(0)
            .perform(longClick());
    onView(withId(R.id.favoriteAction)).perform(click());
    pressBack();
    pressBack();

    onData(is(instanceOf(Cursor.class))).inAdapterView(withId(android.R.id.list)).atPosition(0)
            .perform(longClick());
    onView(withId(R.id.removeFromFavorites)).perform(click());

    onView(withId(android.R.id.list)).check(hasTotalCount(0));
    onView(withId(android.R.id.empty))
            .check(matches(allOf(withText(R.string.f_empty_list_msg), isDisplayed())));
}