List of usage examples for android.app Activity isFinishing
public boolean isFinishing()
From source file:com.serenegiant.aceparrot.BaseFragment.java
protected void showToast(@StringRes final int messageId, @Duration final int duration) { runOnUiThread(new Runnable() { @Override/*from ww w .j a v a 2 s. c o m*/ public void run() { if (mToast != null) { mToast.cancel(); mToast = null; } final Activity activity = getActivity(); if ((activity == null) || activity.isFinishing()) return; mToast = Toast.makeText(activity, messageId, duration); mToast.show(); } }); }
From source file:nl.eduvpn.app.fragment.HomeFragment.java
/** * Checks if the loading has finished.//from w w w. j av a 2 s . com * If yes, it hides the loading animation. * If there were any errors, it will display a warning bar as well. * * @param adapter The adapter which the items are being loaded into. */ private synchronized void _checkLoadingFinished(final ProfileAdapter adapter) { _pendingInstanceCount--; if (_pendingInstanceCount <= 0 && _problematicInstances.size() == 0) { if (_loadingBar == null) { Log.d(TAG, "Layout has been destroyed already."); return; } float startHeight = _loadingBar.getHeight(); ValueAnimator animator = ValueAnimator.ofFloat(startHeight, 0); animator.setDuration(600); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float fraction = animation.getAnimatedFraction(); float alpha = 1f - fraction; float height = (Float) animation.getAnimatedValue(); if (_loadingBar != null) { _loadingBar.setAlpha(alpha); _loadingBar.getLayoutParams().height = (int) height; _loadingBar.requestLayout(); } } }); animator.start(); } else if (_pendingInstanceCount <= 0) { if (_displayText == null) { Log.d(TAG, "Layout has been destroyed already."); return; } // There are some warnings _displayText.setText(R.string.could_not_fetch_all_profiles); _warningIcon.setVisibility(View.VISIBLE); _progressBar.setVisibility(View.GONE); _loadingBar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Display a dialog with all the warnings _currentDialog = ErrorDialog.show(getContext(), getString(R.string.warnings_list), getString(R.string.instance_access_warning_message), new ErrorDialog.InstanceWarningHandler() { @Override public List<Instance> getInstances() { return _problematicInstances; } @Override public void retryInstance(Instance instance) { _warningIcon.setVisibility(View.GONE); _progressBar.setVisibility(View.VISIBLE); _displayText.setText(R.string.loading_available_profiles); SavedAuthState savedAuthState = _historyService.getSavedToken(instance); if (savedAuthState == null) { // Should never happen _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.data_removed); } else { // Retry _problematicInstances.remove(instance); _fillList(adapter, Collections.singletonList(savedAuthState)); } } @Override public void loginInstance(final Instance instance) { // Find the auth state for the instance and then retry AuthState authState = _historyService.getCachedAuthState(instance); _apiService.getJSON( instance.getSanitizedBaseURI() + Constants.API_DISCOVERY_POSTFIX, authState, new APIService.Callback<JSONObject>() { @Override public void onSuccess(JSONObject result) { try { DiscoveredAPI discoveredAPI = _serializerService .deserializeDiscoveredAPI(result); // Cache the result _historyService.cacheDiscoveredAPI( instance.getSanitizedBaseURI(), discoveredAPI); _problematicInstances.remove(instance); Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { _connectionService.initiateConnection(getActivity(), instance, discoveredAPI); } } catch (SerializerService.UnknownFormatException ex) { Log.e(TAG, "Error parsing discovered API!", ex); _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.provider_incorrect_format); } } @Override public void onError(String errorMessage) { Log.e(TAG, "Error while fetching discovered API: " + errorMessage); DiscoveredAPI discoveredAPI = _historyService .getCachedDiscoveredAPI(instance.getSanitizedBaseURI()); Activity activity = getActivity(); if (discoveredAPI != null && activity != null && !activity.isFinishing()) { _connectionService.initiateConnection(activity, instance, discoveredAPI); } else { _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.provider_not_found_retry); } } }); } @Override public void removeInstance(Instance instance) { _historyService.removeAllDataForInstance(instance); _problematicInstances.remove(instance); getActivity().runOnUiThread(() -> _checkLoadingFinished(adapter)); } }); } }); } }
From source file:com.hackensack.umc.activity.ProfileSelfieActivity.java
public void showAlert(Activity activity, String title, String message) { if (!activity.isFinishing()) { android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder( activity);/*w w w . ja va2 s .c o m*/ LayoutInflater inflater = activity.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_network_offline, null); builder.setView(dialogView); if (title.length() > 0) ((TextView) dialogView.findViewById(R.id.dialog_title)).setText(title); else ((TextView) dialogView.findViewById(R.id.dialog_title)).setVisibility(View.GONE); ((TextView) dialogView.findViewById(R.id.text_message)).setText(message); Button btnDismiss = (Button) dialogView.findViewById(R.id.button_dialog_ok); btnDismiss.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { alert.dismiss(); isMessageShown = true; selectedImageView = Constant.SELFIE; imageUri = CameraFunctionality.dispatchTakePictureIntent(ProfileSelfieActivity.this, 1, Constant.SELFIE); } }); alert = builder.show(); } }
From source file:org.appcelerator.titanium.util.TiUIHelper.java
/** * Creates and shows a dialog with an OK button given title and message. * The dialog's creation context is the current activity. * @param title the title of dialog.//from w w w. j a v a2 s . co m * @param message the dialog's message. * @param listener the click listener for click events. */ public static void doOkDialog(final String title, final String message, OnClickListener listener) { if (listener == null) { listener = new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Activity ownerActivity = ((AlertDialog) dialog).getOwnerActivity(); //if activity is not finishing, remove dialog to free memory if (ownerActivity != null && !ownerActivity.isFinishing()) { ((TiBaseActivity) ownerActivity).removeDialog((AlertDialog) dialog); } } }; } final OnClickListener fListener = listener; waitForCurrentActivity(new CurrentActivityListener() { // TODO @Override public void onCurrentActivityReady(final Activity activity) { //add dialog to activity for cleaning up purposes if (!activity.isFinishing()) { AlertDialog dialog = new AlertDialog.Builder(activity).setTitle(title).setMessage(message) .setPositiveButton(android.R.string.ok, fListener).setCancelable(false).create(); if (activity instanceof TiBaseActivity) { TiBaseActivity baseActivity = (TiBaseActivity) activity; baseActivity.addDialog(baseActivity.new DialogWrapper(dialog, true, new WeakReference<TiBaseActivity>(baseActivity))); dialog.setOwnerActivity(activity); } dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { TiApplication.getInstance().cancelPauseEvent(); } }); dialog.show(); } } }); }
From source file:org.solovyev.android.messenger.BaseListFragment.java
protected void onListLoaded() { Log.d(tag, "onListLoaded"); final Activity activity = getActivity(); if (activity != null && !activity.isFinishing() && !isDetached() && fragmentUi.wasViewCreated()) { Log.d(tag, "Restoring list properties"); restoreListViewState();//from w w w . j a va2 s . co m if (restoredAdapterSelection != null) { restoreAdapterSelection(activity, restoredAdapterSelection); } onListLoadedCallNeeded = false; } else { Log.d(tag, "onListLoaded should be called again"); onListLoadedCallNeeded = true; } }
From source file:com.arthurtimberly.fragments.CaptureFragment.java
/** * Checks whether the {@link Activity} is attached and not finishing. This should be used as a validation check in a * runnable posted to the ui thread, and the {@link Activity} may be have detached by the time the runnable * executes. This method should be called on the ui thread. * * @return true if {@link Activity} is still alive; false otherwise. *//*from w w w.java 2 s. co m*/ private boolean isActivityAlive() { Activity activity = getActivity(); return activity != null && !activity.isFinishing(); }
From source file:com.arthurtimberly.fragments.CaptureFragment.java
/** * Kicks off capture in burst mode, which is basically capturing without auto-focus. *//*from w ww .ja va 2 s.com*/ private void kickoffBurstCapture() { mTimer.schedule(new TimerTask() { @Override public void run() { final Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { activity.runOnUiThread(new Runnable() { @Override public void run() { takePicture(); } }); } } }, BURST_DELAY); }
From source file:nl.eduvpn.app.fragment.HomeFragment.java
private void _checkCertificateValidity(Instance instance, DiscoveredAPI discoveredAPI, SavedKeyPair savedKeyPair, Profile profile, AuthState authState, ProgressDialog dialog) { String commonName = savedKeyPair.getKeyPair().getCertificateCommonName(); if (commonName == null) { // Unable to check, better download it again. _historyService.removeSavedKeyPairs(instance); // Try downloading it again. dialog.dismiss();/*from w ww . jav a 2 s. c o m*/ _downloadKeyPairIfNeeded(instance, discoveredAPI, profile, authState); Log.w(TAG, "Could not check if certificate is valid. Downloading again."); } _apiService.getJSON(discoveredAPI.getCheckCertificateEndpoint(commonName), authState, new APIService.Callback<JSONObject>() { @Override public void onSuccess(JSONObject result) { try { Boolean isValid = result.getJSONObject("check_certificate").getJSONObject("data") .getBoolean("is_valid"); if (isValid) { Log.i(TAG, "Certificate appears to be valid."); _downloadProfileWithKeyPair(instance, discoveredAPI, savedKeyPair, profile, authState, dialog); } else { dialog.dismiss(); String reason = result.getJSONObject("check_certificate").getJSONObject("data") .getString("reason"); if ("user_disabled".equals(reason) || "certificate_disabled".equals(reason)) { int errorStringId = R.string.error_certificate_disabled; if ("user_disabled".equals(reason)) { errorStringId = R.string.error_user_disabled; } _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title_invalid_certificate, getString(errorStringId)); } else { // Remove stored keypair. _historyService.removeSavedKeyPairs(instance); Log.i(TAG, "Certificate is invalid. Fetching new one. Reason: " + reason); // Try downloading it again. _downloadKeyPairIfNeeded(instance, discoveredAPI, profile, authState); } } } catch (Exception ex) { dialog.dismiss(); _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, getString(R.string.error_parsing_certificate)); Log.e(TAG, "Unexpected certificate call response!", ex); } } @Override public void onError(String errorMessage) { dialog.dismiss(); if (errorMessage != null && (APIService.USER_NOT_AUTHORIZED_ERROR.equals(errorMessage) || errorMessage.contains("invalid_grant"))) { // Display a dialog with all the warnings _currentDialog = ErrorDialog.show(getContext(), getString(R.string.warnings_list), getString(R.string.instance_access_warning_message), new ErrorDialog.InstanceWarningHandler() { @Override public List<Instance> getInstances() { return Collections.singletonList(instance); } @Override public void retryInstance(Instance instance) { SavedAuthState savedAuthState = _historyService.getSavedToken(instance); if (savedAuthState == null) { // Should never happen _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.data_removed); } else { int dialogMessageRes = R.string.vpn_profile_checking_certificate; final ProgressDialog dialog = ProgressDialog.show(getContext(), getString(R.string.progress_dialog_title), getString(dialogMessageRes), true, false); dialog.show(); _currentDialog = dialog; _checkCertificateValidity(instance, discoveredAPI, savedKeyPair, profile, savedAuthState.getAuthState(), dialog); } } @Override public void loginInstance(final Instance instance) { // Find the auth state for the instance and then retry AuthState authState = _historyService.getCachedAuthState(instance); _apiService.getJSON( instance.getSanitizedBaseURI() + Constants.API_DISCOVERY_POSTFIX, authState, new APIService.Callback<JSONObject>() { @Override public void onSuccess(JSONObject result) { try { DiscoveredAPI discoveredAPI = _serializerService .deserializeDiscoveredAPI(result); // Cache the result _historyService.cacheDiscoveredAPI( instance.getSanitizedBaseURI(), discoveredAPI); _connectionService.initiateConnection(getActivity(), instance, discoveredAPI); } catch (SerializerService.UnknownFormatException ex) { Log.e(TAG, "Error parsing discovered API!", ex); _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.provider_incorrect_format); } } @Override public void onError(String errorMessage) { Log.e(TAG, "Error while fetching discovered API: " + errorMessage); DiscoveredAPI discoveredAPI = _historyService .getCachedDiscoveredAPI( instance.getSanitizedBaseURI()); Activity activity = getActivity(); if (discoveredAPI != null && activity != null && !activity.isFinishing()) { _connectionService.initiateConnection(activity, instance, discoveredAPI); } else { _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, R.string.provider_not_found_retry); } } }); } @Override public void removeInstance(Instance instance) { _historyService.removeAllDataForInstance(instance); } }); } else { _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title, getString(R.string.error_checking_certificate)); Log.e(TAG, "Error checking certificate: " + errorMessage); } } }); }
From source file:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. */// w ww . j a 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); 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:com.arthurtimberly.fragments.CaptureFragment.java
/** * Kicks off countdown and auto-focus, captures frame at the end. *///from w w w. j a v a2 s.c o m private void kickoffCountdownCapture() { // Set visibility of countdown timer. mCountdown.setVisibility(View.VISIBLE); if (mTimer != null) { mTimer.schedule(new TimerTask() { @Override public void run() { final Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (isActivityAlive()) { if (mCountdownThree != null) { mCountdownThree .setTextColor(getResources().getColor(R.color.selection_color)); } mCameraAudioHelper.beep(); // Kick off auto-focus and indicate status. if (mCamera != null) { mCamera.autoFocus(new MyAutoFocusCallback()); } } } }); } } }, COUNTDOWN_STEP_DELAY * 2); mTimer.schedule(new TimerTask() { @Override public void run() { final Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (isActivityAlive()) { if (mCountdownTwo != null) { mCountdownTwo .setTextColor(getResources().getColor(R.color.selection_color)); } mCameraAudioHelper.beep(); } } }); } } }, COUNTDOWN_STEP_DELAY * 3); mTimer.schedule(new TimerTask() { @Override public void run() { final Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (isActivityAlive()) { if (mCountdownOne != null) { mCountdownOne .setTextColor(getResources().getColor(R.color.selection_color)); } mCameraAudioHelper.beep(); } } }); } } }, COUNTDOWN_STEP_DELAY * 4); mTimer.schedule(new TimerTask() { @Override public void run() { final Activity activity = getActivity(); if (activity != null && !activity.isFinishing()) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (isActivityAlive()) { // Reset countdown timer to initial state. resetCountdownTimer(); // Capture frame. takePicture(); } } }); } } }, COUNTDOWN_STEP_DELAY * 5); } }