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

The following examples show how to use android.app.Activity#isDestroyed() . 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
Source File: DialogScene.java    From scene with Apache License 2.0 6 votes vote down vote up
public void show(@NonNull Scene hostScene) {
    if (hostScene.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
        return;
    }
    Activity activity = hostScene.getActivity();
    if (activity == null) {
        return;
    }

    if (activity.isFinishing()) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) {
        return;
    }

    NavigationScene navigationScene = hostScene.getNavigationScene();
    if (navigationScene == null) {
        return;
    }

    navigationScene.push(this, new PushOptions.Builder().setAnimation(new DialogSceneAnimatorExecutor()).setTranslucent(true).build());
}
 
Example 2
Source File: UiUtils.java    From tindroid with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
static void requestAvatar(@Nullable Fragment fragment) {
    if (fragment == null) {
        return;
    }

    final Activity activity = fragment.getActivity();
    if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
        return;
    }

    if (!isPermissionGranted(activity, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
        fragment.requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                READ_EXTERNAL_STORAGE_PERMISSION);
    } else {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);

        fragment.startActivityForResult(Intent.createChooser(intent, fragment.getString(R.string.select_image)),
                ACTIVITY_RESULT_SELECT_PICTURE);
    }
}
 
Example 3
Source File: Utils.java    From AndroidAnimationExercise with Apache License 2.0 6 votes vote down vote up
Activity getTopActivity() {
    if (!mActivityList.isEmpty()) {
        for (int i = mActivityList.size() - 1; i >= 0; i--) {
            Activity activity = mActivityList.get(i);
            if (activity == null
                    || activity.isFinishing()
                    || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed())) {
                continue;
            }
            return activity;
        }
    }
    Activity topActivityByReflect = getTopActivityByReflect();
    if (topActivityByReflect != null) {
        setTopActivity(topActivityByReflect);
    }
    return topActivityByReflect;
}
 
Example 4
Source File: SirenAlertWrapper.java    From Siren with MIT License 6 votes vote down vote up
public void show() {
    Activity activity = mActivityRef.get();
    if (activity == null) {
        if (mSirenListener != null) {
            mSirenListener.onError(new NullPointerException("activity reference is null"));
        }
    } else if (Build.VERSION.SDK_INT >= 17 && !activity.isDestroyed() || Build.VERSION.SDK_INT < 17 && !activity.isFinishing()) {

        AlertDialog alertDialog = initDialog(activity);
        setupDialog(alertDialog);

        if (mSirenListener != null) {
            mSirenListener.onShowUpdateDialog();
        }
    }
}
 
Example 5
Source File: Exceptions.java    From SystemUITuner2 with MIT License 6 votes vote down vote up
public void secureSettings(Activity activity, final Context appContext, Exception e, String page) { //exception function for a Secure Settings problem
    Log.e(page, e.getMessage()); //log the error
    e.printStackTrace();

    if (!activity.isDestroyed()) {
        new AlertDialog.Builder(activity) //show a dialog with the error and prompt user to set up permissions again
                .setIcon(alertRed)
                .setTitle(Html.fromHtml("<font color='#ff0000'>" + activity.getResources().getText(R.string.error) + "</font>"))
                .setMessage(activity.getResources().getText(R.string.perms_not_set) + "\n\n\"" + e.getMessage() + "\"\n\n" + activity.getResources().getText(R.string.prompt_setup))
                .setPositiveButton(activity.getResources().getText(R.string.yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(appContext, SetupActivity.class);
                        intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
                        appContext.startActivity(intent);
                    }
                })
                .setNegativeButton(activity.getResources().getText(R.string.no), null)
                .show();
    }
}
 
Example 6
Source File: UpdateCheckActivity.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPostExecute(Boolean result) {
    // Re-acquire a strong reference to the weakReference, and verify
    // that it still exists and is active.
    Activity activity = this.weakReference.get();
    if (activity == null || activity.isFinishing()
            || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed())) {
        return;
    }
    Context context = activity.getApplicationContext();
    if (result) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, "Download Completed: " + name, Toast.LENGTH_LONG).show();
            }
        }, LOAD_DELAY);
    } else {
        Toast.makeText(context, "failed to read data", Toast.LENGTH_SHORT).show();
    }
}
 
Example 7
Source File: UpdateCheckActivity.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPostExecute(Boolean result) {
    // Re-acquire a strong reference to the weakReference, and verify
    // that it still exists and is active.
    Activity activity = this.weakReference.get();
    if (activity == null || activity.isFinishing()
            || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed())) {
        return;
    }
    Context context = activity.getApplicationContext();
    if (result) {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, "Download Completed: " + name, Toast.LENGTH_LONG).show();
            }
        }, LOAD_DELAY);
    } else {
        Toast.makeText(context, "failed to read data", Toast.LENGTH_SHORT).show();
    }
}
 
Example 8
Source File: DefaultDesignUIController.java    From AgentWeb with Apache License 2.0 6 votes vote down vote up
private void onJsAlertInternal(WebView view, String message) {
    Activity mActivity = this.mActivity;
    if (mActivity == null || mActivity.isFinishing()) {
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        if (mActivity.isDestroyed()) {
            return;
        }
    }
    try {
        AgentWebUtils.show(view,
                message,
                Snackbar.LENGTH_SHORT,
                Color.WHITE,
                mActivity.getResources().getColor(R.color.black),
                null,
                -1,
                null);
    } catch (Throwable throwable) {
        if (LogUtils.isDebug()){
            throwable.printStackTrace();
        }
    }
}
 
Example 9
Source File: LoadFrameTask.java    From PLDroidShortVideo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onProgressUpdate(PLVideoFrame... values) {
    super.onProgressUpdate(values);

    Activity activity = weakActivity.get();
    if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
        return;
    }

    PLVideoFrame frame = values[0];
    if (mOnLoadFrameListener != null) {
        mOnLoadFrameListener.onFrameReady(frame == null ? null : frame.toBitmap());
    }
}
 
Example 10
Source File: ContextUtil.java    From YalpStore with GNU General Public License v2.0 5 votes vote down vote up
static public boolean isAlive(Context context) {
    if (!(context instanceof Activity)) {
        return false;
    }
    Activity activity = (Activity) context;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return !activity.isDestroyed();
    } else {
        return !activity.isFinishing();
    }
}
 
Example 11
Source File: UiUtils.java    From tindroid with Apache License 2.0 5 votes vote down vote up
static void setupToolbar(final Activity activity, final VxCard pub,
                         final String topicName, final boolean online, final Date lastSeen) {
    if (activity == null || activity.isDestroyed() || activity.isFinishing()) {
        return;
    }

    final Toolbar toolbar = activity.findViewById(R.id.toolbar);
    if (toolbar == null) {
        return;
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (!TextUtils.isEmpty(topicName)) {
                final String title = pub != null && pub.fn != null ?
                        pub.fn : activity.getString(R.string.placeholder_contact_title);
                toolbar.setTitle(title);
                if (lastSeen != null && !online) {
                    toolbar.setSubtitle(relativeDateFormat(activity, lastSeen));
                } else {
                    toolbar.setSubtitle(null);
                }
                constructToolbarLogo(activity, pub != null ? pub.getBitmap() : null,
                        pub != null ? pub.fn  : null, topicName, online);
            } else {
                toolbar.setTitle(R.string.app_name);
                toolbar.setSubtitle(null);
                toolbar.setLogo(null);
            }
        }
    });
}
 
Example 12
Source File: Exceptions.java    From SystemUITuner2 with MIT License 5 votes vote down vote up
public void systemSettings(Activity activity, final Context appContext, Exception e, String page) { //exceptions for System Settings (should only be needed on API > 22)
    Log.e(page, e.getMessage()); //log error
    e.printStackTrace();

    if (!activity.isDestroyed()) {
        new AlertDialog.Builder(activity) //show details dialog
                .setIcon(alertRed)
                .setTitle(Html.fromHtml("<font color='#ff0000'>" + activity.getResources().getText(R.string.error) + "</font>"))
                .setMessage(activity.getResources().getText(R.string.system_settings_failed) + "\n\n\"" + e.getMessage() + "\"")
                .setPositiveButton(activity.getResources().getText(R.string.ok), null)
                .show();
    }
}
 
Example 13
Source File: AppManager.java    From ImmersionBar with Apache License 2.0 5 votes vote down vote up
public <T extends Activity> boolean hasActivity(Class<T> tClass) {
    for (Activity activity : mActivities) {
        if (tClass.getName().equals(activity.getClass().getName())) {
            return !activity.isDestroyed() || !activity.isFinishing();
        }
    }
    return false;
}
 
Example 14
Source File: AndroidLifecycleUtils.java    From PhotoPicker with Apache License 2.0 5 votes vote down vote up
public static boolean canLoadImage(Activity activity) {
    if (activity == null) {
        return true;
    }

    boolean destroyed = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
            activity.isDestroyed();

    if (destroyed || activity.isFinishing()) {
        return false;
    }

    return true;
}
 
Example 15
Source File: UiUtils.java    From tindroid with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version.
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private static Bitmap loadContactPhotoThumbnail(Fragment fragment, String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!fragment.isAdded()) {
        return null;
    }

    Activity activity = fragment.getActivity();
    if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    Uri thumbUri = Uri.parse(photoData);
    try (AssetFileDescriptor afd = activity.getContentResolver().openAssetFileDescriptor(thumbUri, "r")) {

        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        if (afd != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromStream(
                    new BufferedInputStream(new FileInputStream(afd.getFileDescriptor())), imageSize, imageSize);
        }
    } catch (IOException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
                    + ": " + e.toString());
        }
    }
    // If an AssetFileDescriptor was returned, try to close it
    // Closing a file descriptor might cause an IOException if the file is
    // already closed. Nothing extra is needed to handle this.

    // If the decoding failed, returns null
    return null;
}
 
Example 16
Source File: ActivityUtil.java    From FriendCircle with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 检查activity是否存活
 */
public static boolean isAlive(Activity act) {
    if (act == null) return false;
    return !act.isFinishing() && !act.isDestroyed();
}
 
Example 17
Source File: ImageLoader.java    From qvod with MIT License 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void load(Activity activity, String url, ImageView iv) {    //使用Glide加载ImageView(如头像)时,不要使用占位图
    if (!activity.isDestroyed()) {
        Glide.with(activity).load(url).crossFade().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(iv);
    }
}
 
Example 18
Source File: MessagesFragment.java    From tindroid with Apache License 2.0 4 votes vote down vote up
private void openImageSelector(@Nullable Activity activity) {
    if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
        return;
    }

    if (!UiUtils.isPermissionGranted(activity, Manifest.permission.CAMERA)) {
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                ATTACH_IMAGE_PERMISSIONS);
        return;
    }

    // Pick image from gallery.
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/jpeg", "image/png"});

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Make sure camera is available.
    if (cameraIntent.resolveActivity(activity.getPackageManager()) != null) {
        // Create temp file for storing the photo.
        File photoFile = null;
        try {
            photoFile = createImageFile(activity);
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.w(TAG, "Unable to create temp file for storing camera photo", ex);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoUri = FileProvider.getUriForFile(activity,
                    "co.tinode.tindroid.provider", photoFile);

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            // See explanation here: http://medium.com/@quiro91/ceb9bb0eec3a
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                cameraIntent.setClipData(ClipData.newRawUri("", photoUri));
                cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

            mCurrentPhotoFile = photoFile.getAbsolutePath();
            mCurrentPhotoUri = photoUri;

        } else {
            cameraIntent = null;
        }
    } else {
        cameraIntent = null;
    }

    // Pack two intents into a chooser.
    Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.select_image));
    if (cameraIntent != null) {
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{cameraIntent});
    }

    startActivityForResult(chooserIntent, ACTION_ATTACH_IMAGE);
}
 
Example 19
Source File: PermissionUtils.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
public void needCalendar(@NonNull final Activity act, boolean force) {
    if (act.isDestroyed())
        return;

    if (!pCalendar && (!"-1".equals(Preferences.CALENDAR_INTEGRATION.get()) || force)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(act);

        builder.setTitle(R.string.permissionCalendarTitle).setMessage(R.string.permissionCalendarText)
                .setPositiveButton(R.string.ok, (dialogInterface, i) -> ActivityCompat.requestPermissions(act, new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, 0));


        builder.show();
    }

}
 
Example 20
Source File: TopicInfoFragment.java    From tindroid with Apache License 2.0 4 votes vote down vote up
private void notifyContentChanged() {

        final Activity activity = getActivity();
        if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
            return;
        }

        final AppCompatImageView avatar = activity.findViewById(R.id.imageAvatar);
        final TextView title = activity.findViewById(R.id.topicTitle);
        final TextView subtitle = activity.findViewById(R.id.topicSubtitle);

        VxCard pub = mTopic.getPub();
        if (pub != null && !TextUtils.isEmpty(pub.fn)) {
            title.setText(pub.fn);
            title.setTypeface(null, Typeface.NORMAL);
            title.setTextIsSelectable(true);
        } else {
            title.setText(R.string.placeholder_contact_title);
            title.setTypeface(null, Typeface.ITALIC);
            title.setTextIsSelectable(false);
        }

        final Bitmap bmp = pub != null ? pub.getBitmap() : null;
        if (bmp != null) {
            avatar.setImageDrawable(new RoundImageDrawable(getResources(), bmp));
        } else {
            avatar.setImageDrawable(
                    new LetterTileDrawable(requireContext())
                            .setIsCircular(true)
                            .setContactTypeAndColor(
                                    mTopic.getTopicType() == Topic.TopicType.P2P ?
                                            LetterTileDrawable.ContactType.PERSON :
                                            LetterTileDrawable.ContactType.GROUP)
                            .setLetterAndColor(pub != null ? pub.fn : null, mTopic.getName()));
        }

        PrivateType priv = mTopic.getPriv();
        if (priv != null && !TextUtils.isEmpty(priv.getComment())) {
            subtitle.setText(priv.getComment());
            subtitle.setTypeface(null, Typeface.NORMAL);
            TypedValue typedValue = new TypedValue();
            Resources.Theme theme = getActivity().getTheme();
            theme.resolveAttribute(android.R.attr.textColorSecondary, typedValue, true);
            TypedArray arr = activity.obtainStyledAttributes(typedValue.data,
                    new int[]{android.R.attr.textColorSecondary});
            subtitle.setTextColor(arr.getColor(0, -1));
            arr.recycle();
            subtitle.setTextIsSelectable(true);
        } else {
            subtitle.setText(R.string.placeholder_private);
            subtitle.setTypeface(null, Typeface.ITALIC);
            subtitle.setTextColor(getResources().getColor(R.color.colorTextPlaceholder));
            subtitle.setTextIsSelectable(false);
        }

        ((Switch) activity.findViewById(R.id.switchMuted)).setChecked(mTopic.isMuted());
        ((Switch) activity.findViewById(R.id.switchArchived)).setChecked(mTopic.isArchived());

        Acs acs = mTopic.getAccessMode();
        ((TextView) activity.findViewById(R.id.permissionsSingle)).setText(acs == null ? "" : acs.getMode());
    }