Java Code Examples for android.app.Activity#setResult()

The following examples show how to use android.app.Activity#setResult() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public void onClick (View view) {
    int position = getAdapterPosition();
    Integer color = mColorOptionsDataSet.get(position);

    Log.d(TAG, "Color: " + color + " onClick() position: " + position);

    Activity activity = (Activity) view.getContext();

    if (mSharedPrefString != null && !mSharedPrefString.isEmpty()) {
        SharedPreferences sharedPref = activity.getSharedPreferences(
                activity.getString(R.string.analog_complication_preference_file_key),
                Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(mSharedPrefString, color);
        editor.commit();

        // Let's Complication Config Activity know there was an update to colors.
        activity.setResult(Activity.RESULT_OK);
    }
    activity.finish();
}
 
Example 2
public static void clearUserData(final Activity activity) {
    StandardAlertDialog d =
            new StandardAlertDialog(activity,
                    Localization.get("clear.user.data.warning.title"),
                    Localization.get("clear.user.data.warning.message"));
    DialogInterface.OnClickListener listener = (dialog, which) -> {
        if (which == AlertDialog.BUTTON_POSITIVE) {
            AppUtils.clearUserData();
            activity.setResult(RESULT_DATA_RESET);
            activity.finish();
        }
        dialog.dismiss();
    };
    d.setPositiveButton(StringUtils.getStringRobust(activity, R.string.ok), listener);
    d.setNegativeButton(StringUtils.getStringRobust(activity, R.string.cancel), listener);
    d.showNonPersistentDialog();
}
 
Example 3
private void tearDownAuthorization() {
    Activity activity = getActivity();

    Preferences.of(activity).host().delete();
    Preferences.of(activity).port().delete();
    Preferences.of(activity).personaId().delete();
    Preferences.of(activity).personaName().delete();
    Preferences.of(activity).environment().delete();

    // TODO: remove after upstream fix.
    // https://issues.jboss.org/browse/AGDROID-485
    Cookies.clear();

    activity.setResult(Activity.RESULT_OK);
    activity.finish();
}
 
Example 4
/**
 * 返回上一个Activity
 *
 * @param old     当前Activity的Context
 * @param mBundle
 */
public static void back(Context old, Bundle mBundle, boolean isAffinity) {
    Activity activity = (Activity) old;
    Intent intent = activity.getIntent();
    if (mBundle != null) {
        mBundle.putBoolean(BUNDLE_ACTIVITY_UPDATE, true);
        intent.putExtras(mBundle);
    }
    if (isAffinity) {
        activity.setResult(Activity.RESULT_CANCELED);
        ActivityCompat.finishAffinity(activity);
    } else {
        activity.setResult(Activity.RESULT_OK, intent);
        activity.finish();
    }
}
 
Example 5
@Test
@UiThreadTest
public void shouldReturnActivityResult() {
  // We need to use a real Activity (no mock) here in order to capture the result.
  // The Activity we use is android.app.Activity which exists on all API levels.
  Activity activity = rule.getActivity();
  activity.setResult(Activity.RESULT_OK, new Intent(Intent.ACTION_VIEW));

  activity.finish(); // must be called on the UI Thread

  ActivityResult activityResult = rule.getActivityResult();
  assertNotNull(activityResult);
  assertEquals(Activity.RESULT_OK, activityResult.getResultCode());
  assertEquals(Intent.ACTION_VIEW, activityResult.getResultData().getAction());
}
 
Example 6
/**
 * 在Activity.onBackPressed()中执行的方法,请不要执行onBackPressed()的super方法体
 * 这时候已经可以确保要执行动画的view显示完成了,所以可以安全的执行这个方法
 * 
 * @param activity
 */
public static void finishAfterTransition(Activity activity) {
	if (isPlaying) {
		return;
	}
	isEnter = false;
	activity.setResult(ActivityOptionsCompatICS.RESULT_CODE);
	mListener = new TransitionCompat().new MyTransitionListener();
	//开始执行动画,这里的false表示执行结束的动画
	switch (mAnimationType) {
	
	case ActivityOptionsCompatICS.ANIM_SCALE_UP:
		scaleUpAnimation(activity, false);
		break;
	case ActivityOptionsCompatICS.ANIM_THUMBNAIL_SCALE_UP:
		thumbnailScaleUpAnimation(activity, false);
		break;
	case ActivityOptionsCompatICS.ANIM_SCENE_TRANSITION:
		sceneTransitionAnimation(activity, mLayoutResId, false);
		break;
	case ActivityOptionsCompatICS.ANIM_NONE:
		activity.finish();
		return;
	default:
		activity.finish();
		return;
	}
	//执行场景退出的动画
	if (mTransitionAnims != null) {
		
		mTransitionAnims.setAnimsInterpolator(mInterpolator);
		mTransitionAnims.setAnimsStartDelay(mStartDelay);
		mTransitionAnims.setAnimsDuration(mAnimTime);
		mTransitionAnims.addListener(mListener);
		mTransitionAnims.playScreenExitAnims();
	}
	mTransitionAnims = null;
}
 
Example 7
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Activity activity = getActivity();

    switch (requestCode) {
        case REQUEST_PROVISION_MANAGED_PROFILE:
        case REQUEST_PROVISION_DEVICE_OWNER:
            if (resultCode == Activity.RESULT_OK) {
                // Success, finish the enclosing activity. NOTE: Only finish once we're done
                // here, as in synchronous auth cases we don't want the user to return to the
                // Android setup wizard or add-account flow prematurely.
                activity.setResult(Activity.RESULT_OK);
                activity.finish();
            } else {
                // Something went wrong (either provisioning failed, or the user backed out).
                // Let the user decide how to proceed.
                Toast.makeText(activity, R.string.provisioning_failed_or_cancelled,
                        Toast.LENGTH_SHORT).show();
            }
            break;
        case REQUEST_GET_LOGO:
            if (data != null && data.getData() != null) {
                mLogoUri = data.getData();
                mLogoValue.setText(mLogoUri.getLastPathSegment());
                Util.updateImageView(getActivity(), mLogoPreviewView, mLogoUri);
            }
            break;
    }
}
 
Example 8
Source Project: SteamGifts   File: EditCommentTask.java    License: MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(Connection.Response response) {
    Activity activity = getFragment();
    if (response != null && response.statusCode() == 200) {
        try {
            Log.v(TAG, "Response to JSON request: " + response.body());
            JSONObject root = new JSONObject(response.body());

            boolean success = "success".equals(root.getString("type"));
            if (success) {
                Document commentHtml = Jsoup.parse(root.getString("comment"));

                // Save the content of the edit state for a bit & remove the edit state from being rendered.
                Element editState = commentHtml.select(".comment__edit-state.is-hidden textarea[name=description]").first();
                commentHtml.select(".comment__edit-state").html("");
                Element desc = commentHtml.select(".comment__description").first();

                if (editState == null)
                    Log.d(TAG, "edit state is null?");
                comment.setEditableContent(editState == null ? null : editState.text());
                comment.setContent(desc.html());

                Intent data = new Intent();
                data.putExtra("edited-comment", comment);
                activity.setResult(WriteCommentActivity.COMMENT_EDIT_SENT, data);
                activity.finish();

                return;
            }
        } catch (JSONException e) {
            Log.e(TAG, "Failed to parse JSON object", e);
        }
    }
    onFail();
}
 
Example 9
/**
 * 在Activity.onBackPressed()中执行的方法,请不要执行onBackPressed()的super方法体
 * 这时候已经可以确保要执行动画的view显示完成了,所以可以安全的执行这个方法
 * 
 * @param activity
 */
public static void finishAfterTransition(Activity activity) {
	if (isPlaying) {
		return;
	}
	isEnter = false;
	activity.setResult(ActivityOptionsCompatICS.RESULT_CODE);
	mListener = new TransitionCompat().new MyTransitionListener();
	//开始执行动画,这里的false表示执行结束的动画
	switch (mAnimationType) {
	
	case ActivityOptionsCompatICS.ANIM_SCALE_UP:
		scaleUpAnimation(activity, false);
		break;
	case ActivityOptionsCompatICS.ANIM_THUMBNAIL_SCALE_UP:
		thumbnailScaleUpAnimation(activity, false);
		break;
	case ActivityOptionsCompatICS.ANIM_SCENE_TRANSITION:
		sceneTransitionAnimation(activity, mLayoutResId, false);
		break;
	case ActivityOptionsCompatICS.ANIM_NONE:
		activity.finish();
		return;
	default:
		activity.finish();
		return;
	}
	//执行场景退出的动画
	if (mTransitionAnims != null) {
		
		mTransitionAnims.setAnimsInterpolator(mInterpolator);
		mTransitionAnims.setAnimsStartDelay(mStartDelay);
		mTransitionAnims.setAnimsDuration(mAnimTime);
		mTransitionAnims.addListener(mListener);
		mTransitionAnims.playScreenExitAnims();
	}
	mTransitionAnims = null;
}
 
Example 10
Source Project: CrimeTalk-Reader   File: ThemeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the theme of the current {@link android.app.Activity}.
 * This will close and restart the calling {@link android.app.Activity}.
 *
 * @param activity The current {@link android.app.Activity}
 */
public static void setThemeImmediately(Activity activity) {

    final Intent intent = new Intent();
    activity.setResult(Activity.RESULT_OK, intent);

    activity.finish();
    activity.startActivity(new Intent(activity, activity.getClass()));
    activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

}
 
Example 11
Source Project: YiBo   File: DestroyStatusTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onPostExecute(Boolean result) {
	super.onPostExecute(result);
	if (dialog != null &&
		dialog.getContext() != null
	) {
		try {
		    dialog.dismiss();
		} catch (Exception e) {}
	}

	if (result) {
		resultMsg = context.getString(R.string.msg_blog_delete_success);
	}
	if (result && isCloseContext) {
           Activity activity = (Activity)context;

           Intent intent = new Intent();
           Bundle bundle = new Bundle();
           bundle.putSerializable("STATUS", status);
           intent.putExtras(bundle);

           activity.setResult(Constants.RESULT_CODE_MICRO_BLOG_DELETE, intent);
           activity.finish();
	} else if (result) {
		adapter.remove(status);
	}

	Toast.makeText(context, resultMsg, Toast.LENGTH_SHORT).show();
}
 
Example 12
Source Project: mv2m   File: ActivityHolder.java    License: Apache License 2.0 5 votes vote down vote up
public void finishActivity(ActivityResult result) {
    Activity activity = getActivity();
    if (activity != null) {
        Intent intent = new Intent();
        intent.putExtra(ViewModelManager.RESULT_DATA, result.getData());
        activity.setResult(result.isResultOk() ? Activity.RESULT_OK : Activity.RESULT_CANCELED, intent);
        activity.finish();
    }
}
 
Example 13
public static void backResult(Activity sourceActivity, int resultCode, Bundle bdl) {
    Intent intent = new Intent();
    if (bdl != null) {
        intent.putExtras(bdl);
    }
    sourceActivity.setResult(resultCode, intent);
}
 
Example 14
Source Project: delion   File: FirstRunActivity.java    License: Apache License 2.0 5 votes vote down vote up
protected static void finishAllFREActivities(int result, Intent data) {
    List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities();
    for (WeakReference<Activity> weakActivity : activities) {
        Activity activity = weakActivity.get();
        if (activity instanceof FirstRunActivity) {
            activity.setResult(result, data);
            activity.finish();
        }
    }
}
 
Example 15
Source Project: native-navigation   File: NavigatorModule.java    License: MIT License 5 votes vote down vote up
private void dismiss(Activity activity, ReadableMap payload) {
  Intent intent = new Intent()
      .putExtra(EXTRA_PAYLOAD, payloadToMap(payload));
  if (activity instanceof ReactInterface) {
    // TODO: 10/6/16 emily this doesn't work for ReactNativeFragment
    intent.putExtra(EXTRA_IS_DISMISS, ((ReactInterface) activity).isDismissible());
  }
  activity.setResult(getResultCodeFromPayload(payload), intent);
  activity.finish();
}
 
Example 16
public static void executeError(Activity activity, int code) {
    activity.setResult(code);
    activity.finish();
}
 
Example 17
/**
 * Tries to launch the First Run Experience.  If ChromeLauncherActivity is running with the
 * wrong Intent flags, we instead relaunch ChromeLauncherActivity to make sure it runs in its
 * own task, which then triggers First Run.
 * @return Whether or not the First Run Experience needed to be shown.
 * @param forTabbedMode Whether the First Run Experience is launched for tabbed mode.
 */
private boolean launchFirstRunExperience(boolean forTabbedMode) {
    // Tries to launch the Generic First Run Experience for intent from GSA.
    boolean showLightweightFre =
            IntentHandler.determineExternalIntentSource(this.getPackageName(), getIntent())
            != ExternalAppId.GSA;
    Intent freIntent = FirstRunFlowSequencer.checkIfFirstRunIsNecessary(
            this, getIntent(), showLightweightFre);
    if (freIntent == null) return false;

    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        if (CommandLine.getInstance().hasSwitch(
                    ChromeSwitches.ENABLE_LIGHTWEIGHT_FIRST_RUN_EXPERIENCE)) {
            boolean isTabbedModeActive = false;
            boolean isLightweightFreActive = false;
            boolean isGenericFreActive = false;
            List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities();
            for (WeakReference<Activity> weakActivity : activities) {
                Activity activity = weakActivity.get();
                if (activity == null) {
                    continue;
                }

                if (activity instanceof ChromeTabbedActivity) {
                    isTabbedModeActive = true;
                    continue;
                }

                if (activity instanceof LightweightFirstRunActivity) {
                    isLightweightFreActive = true;
                    // A Generic or a new Lightweight First Run Experience will be launched
                    // below, so finish the old Lightweight First Run Experience.
                    activity.setResult(Activity.RESULT_CANCELED);
                    activity.finish();
                    continue;
                }

                if (activity instanceof FirstRunActivity) {
                    isGenericFreActive = true;
                    continue;
                }
            }

            if (forTabbedMode) {
                if (isTabbedModeActive || isLightweightFreActive || !showLightweightFre) {
                    // Lets ChromeTabbedActivity checks and launches the Generic First Run
                    // Experience.
                    launchTabbedMode(false);
                    finish();
                    return true;
                }
            } else if (isGenericFreActive) {
                // Launch the Generic First Run Experience if it is active previously.
                freIntent = FirstRunFlowSequencer.createGenericFirstRunIntent(
                        this, TextUtils.equals(getIntent().getAction(), Intent.ACTION_MAIN));
            }
        }
        // Add a PendingIntent so that the intent used to launch Chrome will be resent when
        // first run is completed or canceled.
        FirstRunFlowSequencer.addPendingIntent(this, freIntent, getIntent());
        freIntent.putExtra(FirstRunActivity.EXTRA_FINISH_ON_TOUCH_OUTSIDE, !forTabbedMode);
        startActivity(freIntent);
    } else {
        Intent newIntent = new Intent(getIntent());
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(newIntent);
    }
    finish();
    return true;
}
 
Example 18
public static void executeError(Activity activity, int code) {
    activity.setResult(code);
    activity.finish();
}
 
Example 19
/**
 * Tries to launch the First Run Experience.  If the Activity was launched with the wrong Intent
 * flags, we first relaunch it to make sure it runs in its own task, then trigger First Run.
 *
 * @param caller            Activity instance that is checking if first run is necessary.
 * @param intent            Intent used to launch the caller.
 * @param requiresBroadcast Whether or not the Intent triggers a BroadcastReceiver.
 * @return Whether startup must be blocked (e.g. via Activity#finish or dropping the Intent).
 */
public static boolean launch(Context caller, Intent intent, boolean requiresBroadcast) {
    // Check if the user just came back from the FRE.
    boolean firstRunActivityResult = IntentUtils.safeGetBooleanExtra(
            intent, FirstRunActivity.EXTRA_FIRST_RUN_ACTIVITY_RESULT, false);
    boolean firstRunComplete = IntentUtils.safeGetBooleanExtra(
            intent, FirstRunActivity.EXTRA_FIRST_RUN_COMPLETE, false);
    if (firstRunActivityResult && !firstRunComplete) {
        Log.d(TAG, "User failed to complete the FRE.  Aborting");
        return true;
    }

    // Tries to launch the Generic First Run Experience for intent from GSA.
    boolean showLightweightFre =
            IntentHandler.determineExternalIntentSource(caller.getPackageName(), intent)
            != ExternalAppId.GSA;

    // Check if the user needs to go through First Run at all.
    Intent freIntent = checkIfFirstRunIsNecessary(caller, intent, showLightweightFre);
    if (freIntent == null) return false;

    Log.d(TAG, "Redirecting user through FRE.");
    if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        if (CommandLine.getInstance().hasSwitch(
                    ChromeSwitches.ENABLE_LIGHTWEIGHT_FIRST_RUN_EXPERIENCE)) {
            boolean isGenericFreActive = false;
            List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities();
            for (WeakReference<Activity> weakActivity : activities) {
                Activity activity = weakActivity.get();
                if (activity == null) {
                    continue;
                } else if (activity instanceof LightweightFirstRunActivity) {
                    // A Generic or a new Lightweight First Run Experience will be launched
                    // below, so finish the old Lightweight First Run Experience.
                    activity.setResult(Activity.RESULT_CANCELED);
                    activity.finish();
                    continue;
                } else if (activity instanceof FirstRunActivity) {
                    isGenericFreActive = true;
                    continue;
                }
            }

            if (isGenericFreActive) {
                // Launch the Generic First Run Experience if it was previously active.
                freIntent = createGenericFirstRunIntent(
                        caller, TextUtils.equals(intent.getAction(), Intent.ACTION_MAIN));
            }
        }

        // Add a PendingIntent so that the intent used to launch Chrome will be resent when
        // First Run is completed or canceled.
        addPendingIntent(caller, freIntent, intent, requiresBroadcast);
        freIntent.putExtra(FirstRunActivity.EXTRA_FINISH_ON_TOUCH_OUTSIDE, true);

        if (!(caller instanceof Activity)) freIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        IntentUtils.safeStartActivity(caller, freIntent);
    } else {
        // First Run requires that the Intent contains NEW_TASK so that it doesn't sit on top
        // of something else.
        Intent newIntent = new Intent(intent);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        IntentUtils.safeStartActivity(caller, newIntent);
    }
    return true;
}
 
Example 20
Source Project: PhoneProfilesPlus   File: DataWrapper.java    License: Apache License 2.0 4 votes vote down vote up
void activateProfileFromMainThread(final Profile profile, final boolean merged, final int startupSource,
                                final boolean interactive, final Activity _activity, final boolean testGrant)
{
    //PPApplication.logE("$$$$$ DataWrapper.activateProfileFromMainThread", "start");
    final DataWrapper dataWrapper = copyDataWrapper();

    PPApplication.startHandlerThread(/*"DataWrapper.activateProfileFromMainThread"*/);
    final Handler handler = new Handler(PPApplication.handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            PowerManager powerManager = (PowerManager) dataWrapper.context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = null;
            try {
                if (powerManager != null) {
                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":DataWrapper_activateProfileFromMainThread");
                    wakeLock.acquire(10 * 60 * 1000);
                }

                //PPApplication.logE("$$$$$ PPApplication.startHandlerThread", "START run - from=DataWrapper.activateProfileFromMainThread");

                boolean granted = true;
                if (testGrant)
                    granted = !EditorProfilesActivity.displayPreferencesErrorNotification(profile, null, context);
                if (granted) {
                    dataWrapper._activateProfile(profile, merged, startupSource, false);
                    if (interactive) {
                        DatabaseHandler.getInstance(dataWrapper.context).increaseActivationByUserCount(profile);
                        dataWrapper.setDynamicLauncherShortcuts();
                    }
                }

                //PPApplication.logE("$$$$$ PPApplication.startHandlerThread", "END run - from=DataWrapper.activateProfileFromMainThread");
            } finally {
                if ((wakeLock != null) && wakeLock.isHeld()) {
                    try {
                        wakeLock.release();
                    } catch (Exception ignored) {}
                }
            }
        }
    });

    // for startActivityForResult
    if (_activity != null)
    {
        //final Profile profile = _profile; //Profile.getMappedProfile(_profile, context);

        Intent returnIntent = new Intent();
        if (profile == null)
            returnIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, 0);
        else
            returnIntent.putExtra(PPApplication.EXTRA_PROFILE_ID, profile._id);
        returnIntent.putExtra(PPApplication.EXTRA_STARTUP_SOURCE, startupSource);
        _activity.setResult(Activity.RESULT_OK,returnIntent);
    }

    finishActivity(startupSource, true, _activity);

}