Example usage for android.app Activity finish

List of usage examples for android.app Activity finish

Introduction

In this page you can find the example usage for android.app Activity finish.

Prototype

public void finish() 

Source Link

Document

Call this when your activity is done and should be closed.

Usage

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.FavouriteStopsFragment.java

/**
 * {@inheritDoc}/*from   w w w  .  j a v  a 2 s .co m*/
 */
@Override
public void onListItemClick(final ListView l, final View v, final int position, final long id) {
    // Get the stopCode and cache the Activity.
    final String stopCode = String.valueOf(id);
    final Activity activity = getActivity();
    Intent intent;

    // What happens when the user selects a list item depends on what mode
    // is active.
    if (isCreateShortcut) {
        // Set the Intent which is used when the shortcut is tapped.
        intent = new Intent(Intent.ACTION_MAIN);
        intent.setClass(activity, DisplayStopDataActivity.class);
        intent.setAction(DisplayStopDataActivity.ACTION_VIEW_STOP_DATA);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(DisplayStopDataActivity.ARG_STOPCODE, stopCode);

        // Set the Activity result to send back to the launcher, which
        // contains a name, Intent and icon.
        final Intent result = new Intent();
        result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        result.putExtra(Intent.EXTRA_SHORTCUT_NAME, sd.getNameForStop(stopCode));
        final Parcelable icon = Intent.ShortcutIconResource.fromContext(activity, R.drawable.appicon_favourite);
        result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

        // Set the Activity result and exit.
        activity.setResult(Activity.RESULT_OK, result);
        activity.finish();
    } else {
        // View bus stop times.
        callbacks.onShowBusTimes(stopCode);
    }
}

From source file:com.ape.camera2raw.Camera2RawFragment.java

/**
 * Shows that this app really needs the permission and finishes the app.
 */// w  ww .j  av  a 2  s.com
private void showMissingPermissionError() {
    Activity activity = getActivity();
    if (activity != null) {
        Toast.makeText(activity, R.string.request_permission, Toast.LENGTH_SHORT).show();
        activity.finish();
    }
}

From source file:jahirfiquitiva.iconshowcase.activities.ShowcaseActivity.java

private void showNotLicensedDialog(final Activity act, Preferences mPrefs, final String MARKET_URL) {
    mPrefs.setFeaturesEnabled(false);/*from  w  ww . j a  v  a 2s  .com*/
    ISDialogs.showLicenseFailDialog(act, new MaterialDialog.SingleButtonCallback() {
        @Override
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URL + act.getPackageName()));
            act.startActivity(browserIntent);
        }
    }, new MaterialDialog.SingleButtonCallback() {

        @Override
        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
            act.finish();
        }
    }, new MaterialDialog.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            act.finish();
        }
    }, new MaterialDialog.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            act.finish();
        }
    });
}

From source file:cliq.com.cliqgram.fragments.CameraFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Activity activity = getActivity();

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null
            && data.getData() != null) {

        /**/* w  ww .  j av  a2  s  .co  m*/
         * @param imageDate byte[]
         * @param currentUser User
         * @param description String
         * @return post Post
         * Note: Any data in post object may not be able to
         * get before post.saveInBackground() in finished.
         * So, check the database (table "Post") on Parse to see if post is
         * created successfully.
         * If post is created successfully, it will be shown on home page.
         */
        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            startImageDisplayActivity(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        activity.finish();
    }
}

From source file:org.sufficientlysecure.keychain.ui.DecryptListFragment.java

@Override
public void onQueuedOperationSuccess(InputDataResult result) {
    Uri uri = mCurrentInputUri;/*from ww w .j ava  2s.  co m*/
    mCurrentInputUri = null;

    Activity activity = getActivity();

    boolean isSingleInput = mInputDataResults.isEmpty() && mPendingInputUris.isEmpty();
    if (isSingleInput) {

        // there is always at least one mMetadata object, so we know this is >= 1 already
        boolean isSingleMetadata = result.mMetadata.size() == 1;
        OpenPgpMetadata metadata = result.mMetadata.get(0);
        boolean isText = "text/plain".equals(metadata.getMimeType());
        boolean isOverSized = metadata.getOriginalSize() > Constants.TEXT_LENGTH_LIMIT;

        if (isSingleMetadata && isText && !isOverSized) {
            Intent displayTextIntent = new Intent(activity, DisplayTextActivity.class)
                    .setDataAndType(result.mOutputUris.get(0), "text/plain")
                    .putExtra(DisplayTextActivity.EXTRA_RESULT, result.mDecryptVerifyResult)
                    .putExtra(DisplayTextActivity.EXTRA_METADATA, metadata);
            activity.startActivity(displayTextIntent);
            activity.finish();
            return;
        }

    }

    mInputDataResults.put(uri, result);
    processResult(uri);

    cryptoOperation();
}

From source file:com.smartnsoft.droid4me.app.ActivityController.java

/**
 * Indicates whether a redirection is required before letting the activity continue its life cycle. It launches the redirected {@link Activity} if a
 * redirection is need, and provide to its {@link Intent} the initial activity {@link Intent} trough the extra {@link Parcelable}
 * {@link ActivityController#CALLING_INTENT} key.
 * //  w  w  w  .j  av a  2  s  .co  m
 * <p>
 * If the provided {@code activity} implements the {@link ActivityController.EscapeToRedirector} interface or exposes the
 * {@link ActivityController.EscapeToRedirectorAnnotation} annotation, the method returns {@code false}.
 * </p>
 * 
 * <p>
 * Note that this method does not need to be marked as {@code synchronized}, because it is supposed to be invoked systematically from the UI thread.
 * </p>
 * 
 * @param activity
 *          the activity which is being proved against the {@link ActivityController.Redirector}
 * @return {@code true} if and only if the given activity should be paused (or ended) and if another activity should be launched instead through the
 *         {@link Activity#startActivity(Intent)} method
 * @see ActivityController#extractCallingIntent(Activity)
 * @see ActivityController.Redirector#getRedirection(Activity)
 * @see ActivityController.EscapeToRedirector
 * @see ActivityController.EscapeToRedirectorAnnotation
 */
public boolean needsRedirection(Activity activity) {
    if (redirector == null) {
        return false;
    }
    if (activity instanceof ActivityController.EscapeToRedirector || activity.getClass()
            .getAnnotation(ActivityController.EscapeToRedirectorAnnotation.class) != null) {
        if (log.isDebugEnabled()) {
            log.debug("The Activity with class '" + activity.getClass().getName()
                    + "' is escaped regarding the Redirector");
        }
        return false;
    }
    final Intent intent = redirector.getRedirection(activity);
    if (intent == null) {
        return false;
    }
    if (log.isDebugEnabled()) {
        log.debug("A redirection is needed");
    }

    // We redirect to the right Activity
    {
        // We consider the parent activity in case it is embedded (like in an ActivityGroup)
        final Intent formerIntent = activity.getParent() != null ? activity.getParent().getIntent()
                : activity.getIntent();
        intent.putExtra(ActivityController.CALLING_INTENT, formerIntent);
        // Disables the fact that the new started activity should belong to the tasks history and from the recent tasks
        // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        // intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        activity.startActivity(intent);
    }

    // We now finish the redirected Activity
    activity.finish();

    return true;
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Restart the application after 100ms/*from   w ww  .  java2  s  . c om*/
 *
 * @param activity activity
 */
public static void restartApp(Activity activity) {
    // clear the preferences
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = preferences.edit();

    // use the preference to avoid infinite relaunch on some devices
    // the culprit activity is restarted when System.exit is called.
    // so called it once to fix it
    if (!preferences.getBoolean(RESTART_IN_PROGRESS_KEY, false)) {
        CommonActivityUtils.displayToast(activity.getApplicationContext(),
                "Restart the application (low memory)");

        Log.e(LOG_TAG, "Kill the application");
        editor.putBoolean(RESTART_IN_PROGRESS_KEY, true);
        editor.commit();

        PendingIntent mPendingIntent = PendingIntent.getActivity(activity, 314159,
                new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

        // so restart the application after 100ms
        AlarmManager mgr = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);

        System.exit(0);
    } else {
        Log.e(LOG_TAG, "The application is restarting, please wait !!");
        activity.finish();
    }
}

From source file:com.soomla.billing.IabHelper.java

/**
 * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase,
 * which will involve bringing up the Google Play screen. The calling activity will be paused while
 * the user interacts with Google Play, and the result will be delivered via the activity's
 * {@link android.app.Activity#onActivityResult} method, at which point you must call
 * this object's {@link #handleActivityResult} method to continue the purchase flow. This method
 * MUST be called from the UI thread of the Activity.
 *
 * @param act The calling activity.//w w  w . j a v  a 2 s . co m
 * @param sku The sku of the item to purchase.
 * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
 * @param requestCode A request code (to differentiate from other responses --
 *     as in {@link android.app.Activity#startActivityForResult}).
 * @param listener The listener to notify when the purchase process finishes
 * @param extraData Extra data (developer payload), which will be returned with the purchase data
 *     when the purchase completes. This extra data will be permanently bound to that purchase
 *     and will always be returned when the purchase is queried.
 */
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode,
        OnIabPurchaseFinishedListener listener, String extraData) {
    checkSetupDone("launchPurchaseFlow");
    flagStartAsync("launchPurchaseFlow");
    IabResult result;

    if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
        IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
        if (listener != null)
            listener.onIabPurchaseFinished(r, null);
        return;
    }

    try {
        StoreUtils.LogDebug(TAG, "Constructing buy intent for " + sku + ", item type: " + itemType);
        Bundle buyIntentBundle = mService.getBuyIntent(3, SoomlaApp.getAppContext().getPackageName(), sku,
                itemType, extraData);
        buyIntentBundle.putString("PURCHASE_SKU", sku);
        int response = getResponseCodeFromBundle(buyIntentBundle);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            StoreUtils.LogError(TAG, "Unable to buy item, Error response: " + getResponseDesc(response));

            result = new IabResult(response, "Unable to buy item");
            if (listener != null)
                listener.onIabPurchaseFinished(result, null);
            // make sure to end the async operation...
            flagEndAsync();
            act.finish();
            return;
        }

        PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
        StoreUtils.LogDebug(TAG, "Launching buy intent for " + sku + ". Request code: " + requestCode);
        mRequestCode = requestCode;
        mPurchaseListener = listener;
        mPurchasingItemSku = sku;
        mPurchasingItemType = itemType;

        act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(),
                Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
    } catch (SendIntentException e) {
        StoreUtils.LogError(TAG, "SendIntentException while launching purchase flow for sku " + sku);
        e.printStackTrace();

        result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
        if (listener != null)
            listener.onIabPurchaseFinished(result, null);
    } catch (RemoteException e) {
        StoreUtils.LogError(TAG, "RemoteException while launching purchase flow for sku " + sku);
        e.printStackTrace();

        result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
        if (listener != null)
            listener.onIabPurchaseFinished(result, null);
    }
}

From source file:com.example.android.camera2basic.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*from  w  w w  .j  a  v a 2  s  .  c o m*/
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[0];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } catch (NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(),
                FRAGMENT_DIALOG);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:com.lahiru.test.cameraapp.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*from w w w. j a va 2 s . com*/
private void openCamera(int width, int height) {
    if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) {
        requestVideoPermissions();
        return;
    }
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        Log.d(TAG, "tryAcquire");
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = manager.getCameraIdList()[1];

        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
        activity.finish();
    } catch (NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(),
                FRAGMENT_DIALOG);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}