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:pt.iscte.row_timer.android.activities.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*from  w ww.  ja va 2 s . co 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);
        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();
        if (ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        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:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*from ww 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);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);
        Log.d("INFO", "Width and Height: " + width + height);
        Log.d("INFO", "Video Height: " + mVideoSize.getHeight() + " Width: " + mVideoSize.getWidth());
        Log.d("INFO", "Preview Height: " + mPreviewSize.getHeight() + " Width: " + mPreviewSize.getWidth());
        screenInfo = new ScreenInfo();
        screenInfo.setNoSoftKeyScreenInfo(activity);
        Log.d("SCREEN", screenInfo.toString());
        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(kr.ac.kpu.wheeling.R.string.camera_error))
                .show(getChildFragmentManager(), FRAGMENT_DIALOG);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    } catch (SecurityException e) {

    }

}

From source file:de.vanita5.twittnuker.util.Utils.java

public static void restartActivity(final Activity activity) {
    if (activity == null)
        return;//from   www . ja  va  2s  . c  o  m
    final int enter_anim = android.R.anim.fade_in;
    final int exit_anim = android.R.anim.fade_out;
    activity.finish();
    activity.overridePendingTransition(enter_anim, exit_anim);
    activity.startActivity(activity.getIntent());
    activity.overridePendingTransition(enter_anim, exit_anim);
}

From source file:com.android.mms.ui.MessageUtils.java

public static void confirmDeleteMessage(final Activity activity, final Uri msgUri) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.confirm_dialog_title);
    builder.setIconAttribute(android.R.attr.alertDialogIcon);
    builder.setCancelable(true);//ww w .j a va2 s  .c  om
    builder.setMessage(R.string.confirm_delete_message);
    builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            /// M: fix bug ALPS00351620; for requery searchactivity.
            SearchActivity.setNeedRequery();
            SqliteWrapper.delete(activity.getApplicationContext(), activity.getContentResolver(), msgUri, null,
                    null);
            dialog.dismiss();
            activity.finish();
        }
    });
    builder.setNegativeButton(R.string.no, null);
    builder.show();
}

From source file:mgumiero9.com.talentcubetest.view.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//* w  w w  .j  a  v  a  2s.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.e(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);
        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();

        if (ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        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:org.dmfs.tasks.EditTaskFragment.java

/**
 * Persist the current task (if anything has been edited) and close the editor.
 *///from  w w  w . ja  v  a 2 s . c o m
public void saveAndExit() {
    // TODO: put that in a background task
    Activity activity = getActivity();

    int resultCode = Activity.RESULT_CANCELED;
    Intent result = null;
    int toastId = -1;

    if (mEditor != null) {
        mEditor.updateValues();
    }

    if (mValues.isInsert() || mValues.isUpdate()) {
        if (TextUtils.isEmpty(TaskFieldAdapters.TITLE.get(mValues))) {
            // there is no title, try to set one from the description or check list

            String description = TaskFieldAdapters.DESCRIPTION.get(mValues);
            if (description != null) {
                // remove spaces and empty lines
                description = description.trim();
            }

            if (!TextUtils.isEmpty(description)) {
                // we have a description, use it to make up a title
                int eol = description.indexOf('\n');
                TaskFieldAdapters.TITLE.set(mValues, description.substring(0, eol));
            } else {
                // no description, try to find a non-empty checklist item
                List<CheckListItem> checklist = TaskFieldAdapters.CHECKLIST.get(mValues);
                if (checklist != null && checklist.size() > 0) {
                    for (CheckListItem item : checklist) {
                        String trimmedItem = item.text.trim();
                        if (!TextUtils.isEmpty(trimmedItem)) {
                            TaskFieldAdapters.TITLE.set(mValues, trimmedItem);
                            break;
                        }
                    }
                }
            }
        }

        if (!TextUtils.isEmpty(TaskFieldAdapters.TITLE.get(mValues)) || mValues.isUpdate()) {

            if (mValues.updatesAnyKey(RECURRENCE_VALUES)) {
                mValues.ensureUpdates(RECURRENCE_VALUES);
            }

            mTaskUri = mValues.persist(activity);

            // return proper result
            result = new Intent();
            result.setData(mTaskUri);
            resultCode = Activity.RESULT_OK;
            toastId = R.string.activity_edit_task_task_saved;
        } else {
            toastId = R.string.activity_edit_task_empty_task_not_saved;
        }
    } else {
        Log.i(TAG, "nothing to save");
    }

    if (toastId != -1) {
        Toast.makeText(activity, toastId, Toast.LENGTH_SHORT).show();
    }

    if (result != null) {
        activity.setResult(resultCode, result);
    } else {
        activity.setResult(resultCode);
    }

    activity.finish();
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

private void restartActivity() {

    onStop();/*w  w  w  .  j  a  v a  2s. com*/

    // Clear any cached text.
    textLoader.closeCurrentBook();
    Intent intent = new Intent(context, ReadingActivity.class);
    intent.setData(Uri.parse(this.fileName));
    startActivity(intent);
    this.libraryService.close();

    Activity activity = getActivity();

    if (activity != null) {
        activity.finish();
    }
}

From source file:org.uab.deic.uabdroid.solutions.unit5.FormFragment.java

@Override
public void onActivityCreated(Bundle _savedInstanceState) {
    super.onActivityCreated(_savedInstanceState);

    final Activity parentActivity = getActivity();

    SharedPreferences activityPreferences = parentActivity.getPreferences(Context.MODE_PRIVATE);

    mEditTextName = (EditText) parentActivity.findViewById(R.id.edittext_form_name);
    mEditTextDeveloper = (EditText) parentActivity.findViewById(R.id.edittext_form_developer);
    mDatePickerDate = (DatePicker) parentActivity.findViewById(R.id.datepicker_form_date);
    mEditTextURL = (EditText) parentActivity.findViewById(R.id.edittext_form_url);

    if (activityPreferences.getBoolean(FormAppActivity.STATE_NOT_SAVED, false)) {
        mEditTextName.setText(activityPreferences.getString(FormAppActivity.FORM_FIELD_NAME, ""));

        mEditTextDeveloper.setText(activityPreferences.getString(FormAppActivity.FORM_FIELD_DEVELOPER, ""));

        Calendar calendar = Calendar.getInstance();
        int day = activityPreferences.getInt(FormAppActivity.FORM_FIELD_DAY,
                calendar.get(Calendar.DAY_OF_MONTH));
        int month = activityPreferences.getInt(FormAppActivity.FORM_FIELD_MONTH,
                calendar.get(Calendar.MONTH) + 1);
        int year = activityPreferences.getInt(FormAppActivity.FORM_FIELD_YEAR, calendar.get(Calendar.YEAR));

        mDatePickerDate.updateDate(year, month, day);

        mEditTextURL.setText(activityPreferences.getString(FormAppActivity.FORM_FIELD_URL, ""));

        SharedPreferences.Editor editor = activityPreferences.edit();
        editor.putBoolean(FormAppActivity.STATE_NOT_SAVED, false);
        editor.commit();/* w  w w .  ja v a2  s . c o m*/
    }

    Button cleanButton = (Button) parentActivity.findViewById(R.id.button_form_clean);
    cleanButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mEditTextName.setText("");
            mEditTextDeveloper.setText("");
            Calendar calendar = Calendar.getInstance();
            mDatePickerDate.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
                    calendar.get(Calendar.DAY_OF_MONTH));
            mEditTextURL.setText("");
        }
    });

    Button acceptButton = (Button) parentActivity.findViewById(R.id.button_form_accept);
    acceptButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, mDatePickerDate.getDayOfMonth());
            calendar.set(Calendar.MONTH, mDatePickerDate.getMonth() - 1);
            calendar.set(Calendar.YEAR, mDatePickerDate.getYear());

            String name = mEditTextName.getText().toString();
            String developer = mEditTextDeveloper.getText().toString();
            String url = mEditTextURL.getText().toString();

            DatabaseAdapter databaseAdapter = new DatabaseAdapter(parentActivity);
            databaseAdapter.open();
            databaseAdapter.insertApp(name, developer, calendar, url);
            databaseAdapter.close();

            ((FormAppActivity) parentActivity).setButtonPressed();

            parentActivity.finish();
        }
    });

    Button cancelButton = (Button) parentActivity.findViewById(R.id.button_form_cancel);
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ((FormAppActivity) parentActivity).setButtonPressed();
            parentActivity.finish();
        }
    });
}

From source file:com.granita.tasks.EditTaskFragment.java

/**
 * Persist the current task (if anything has been edited) and close the editor.
 *///from   w w w  .  j  a va2 s.c  o m
public void saveAndExit() {
    // TODO: put that in a background task
    Activity activity = getActivity();

    int resultCode = Activity.RESULT_CANCELED;
    Intent result = null;
    int toastId = -1;

    //custom start
    if (mEditor != null) {
        mEditor.updateValues();
    }

    int bogusvar = 1; // set bogus variable
    toastId = R.string.disableedit; //set error message

    if (mValues.isInsert() || mValues.isUpdate())
    //if(bogusvar == 0)
    {
        if (TextUtils.isEmpty(TaskFieldAdapters.TITLE.get(mValues))) {
            // there is no title, try to set one from the description or check list

            String description = TaskFieldAdapters.DESCRIPTION.get(mValues);
            if (description != null) {
                // remove spaces and empty lines
                description = description.trim();
            }

            if (!TextUtils.isEmpty(description)) {
                // we have a description, use it to make up a title
                int eol = description.indexOf('\n');
                TaskFieldAdapters.TITLE.set(mValues, description.substring(0, eol));
            } else {
                // no description, try to find a non-empty checklist item
                List<CheckListItem> checklist = TaskFieldAdapters.CHECKLIST.get(mValues);
                if (checklist != null && checklist.size() > 0) {
                    for (CheckListItem item : checklist) {
                        String trimmedItem = item.text.trim();
                        if (!TextUtils.isEmpty(trimmedItem)) {
                            TaskFieldAdapters.TITLE.set(mValues, trimmedItem);
                            break;
                        }
                    }
                }
            }
        }

        if (!TextUtils.isEmpty(TaskFieldAdapters.TITLE.get(mValues)) || mValues.isUpdate()) {

            if (mValues.updatesAnyKey(RECURRENCE_VALUES)) {
                mValues.ensureUpdates(RECURRENCE_VALUES);
            }

            mTaskUri = mValues.persist(activity);

            // return proper result
            result = new Intent();
            result.setData(mTaskUri);
            resultCode = Activity.RESULT_OK;
            toastId = R.string.activity_edit_task_task_saved;
        } else {
            toastId = R.string.activity_edit_task_empty_task_not_saved;
        }
    } else {
        Log.i(TAG, "nothing to save");
    }

    if (toastId != -1) {
        Toast.makeText(activity, toastId, Toast.LENGTH_SHORT).show();
    }

    if (result != null) {
        activity.setResult(resultCode, result);
    } else {
        activity.setResult(resultCode);
    }

    activity.finish();
}

From source file:org.totschnig.myexpenses.activity.CommonCommands.java

static boolean dispatchCommand(Activity ctx, int command, Object tag) {
    Intent i;//www  . j  a v  a  2s.c  o m
    switch (command) {
    case R.id.RATE_COMMAND:
        i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(MyApplication.getMarketSelfUri()));
        if (Utils.isIntentAvailable(ctx, i)) {
            ctx.startActivity(i);
        } else {
            Toast.makeText(ctx, R.string.error_accessing_market, Toast.LENGTH_LONG).show();
        }
        return true;
    case R.id.SETTINGS_COMMAND:
        i = new Intent(ctx, MyPreferenceActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (tag != null) {
            i.putExtra(MyPreferenceActivity.KEY_OPEN_PREF_KEY, (String) tag);
        }
        ctx.startActivityForResult(i, ProtectedFragmentActivity.PREFERENCES_REQUEST);
        return true;
    case R.id.FEEDBACK_COMMAND:
        i = new Intent(android.content.Intent.ACTION_SEND);
        i.setType("plain/text");
        i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { MyApplication.FEEDBACK_EMAIL });
        i.putExtra(android.content.Intent.EXTRA_SUBJECT, "[" + ctx.getString(R.string.app_name) + "] Feedback");
        i.putExtra(android.content.Intent.EXTRA_TEXT,
                getVersionInfo(ctx) + "\n" + ctx.getString(R.string.feedback_email_message));
        if (!Utils.isIntentAvailable(ctx, i)) {
            Toast.makeText(ctx, R.string.no_app_handling_email_available, Toast.LENGTH_LONG).show();
        } else {
            ctx.startActivity(i);
        }
        break;
    case R.id.CONTRIB_INFO_COMMAND:
        CommonCommands.showContribInfoDialog((FragmentActivity) ctx, -1);
        return true;
    case R.id.WEB_COMMAND:
        i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(ctx.getString(R.string.website)));
        ctx.startActivity(i);
        return true;
    case R.id.HELP_COMMAND:
        i = new Intent(ctx, Help.class);
        i.putExtra(HelpDialogFragment.KEY_VARIANT,
                tag != null ? (Enum<?>) tag : ((ProtectedFragmentActivity) ctx).helpVariant);
        //for result is needed since it allows us to inspect the calling activity
        ctx.startActivityForResult(i, 0);
        return true;
    case R.id.REQUEST_LICENCE_COMMAND:
        String androidId = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
        i = new Intent(android.content.Intent.ACTION_SEND);
        i.setType("plain/text");
        i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { MyApplication.FEEDBACK_EMAIL });
        i.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "[" + ctx.getString(R.string.app_name) + "] " + ctx.getString(R.string.contrib_key));
        String extraText = ctx.getString(R.string.request_licence_mail_head, androidId);
        if (tag != null) {
            extraText += " \n\n[" + ctx.getString(R.string.paypal_transaction_id) + ": " + tag + "]";
        }
        i.putExtra(android.content.Intent.EXTRA_TEXT, extraText);
        if (!Utils.isIntentAvailable(ctx, i)) {
            Toast.makeText(ctx, R.string.no_app_handling_email_available, Toast.LENGTH_LONG).show();
        } else {
            ctx.startActivity(i);
        }
        return true;
    case R.id.VERIFY_LICENCE_COMMAND:
        HashLicenceHandler licenceHandler = (HashLicenceHandler) MyApplication.getInstance()
                .getLicenceHandler();
        LicenceHandler.LicenceStatus licenceStatus = licenceHandler.verifyLicenceKey();
        if (licenceStatus != null) {
            Toast.makeText(ctx,
                    Utils.concatResStrings(ctx, " ", R.string.licence_validation_success,
                            (licenceStatus == LicenceHandler.LicenceStatus.EXTENDED
                                    ? R.string.licence_validation_extended
                                    : R.string.licence_validation_premium)),
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ctx, R.string.licence_validation_failure, Toast.LENGTH_LONG).show();
        }
        licenceHandler.invalidate();
        return true;
    case android.R.id.home:
        ctx.setResult(FragmentActivity.RESULT_CANCELED);
        ctx.finish();
        return true;
    }
    return false;
}