Skip to content

Commit

Permalink
优化判断 Activity 是否可用的代码写法
Browse files Browse the repository at this point in the history
  • Loading branch information
getActivity committed Nov 12, 2023
1 parent 6590f50 commit 5864e2f
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions library/src/main/java/com/hjq/toast/ToastStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,7 @@ public IToast createToast(ToastParams params) {
Settings.canDrawOverlays(mApplication)) {
// 如果有悬浮窗权限,就开启全局的 Toast
toast = new GlobalToast(mApplication);
} else if (!params.crossPageShow && foregroundActivity != null && !foregroundActivity.isFinishing() &&
(VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1 && !foregroundActivity.isDestroyed())) {
} else if (!params.crossPageShow && isActivityAvailable(foregroundActivity)) {
// 如果没有悬浮窗权限,就开启一个依附于 Activity 的 Toast
toast = new ActivityToast(foregroundActivity);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
Expand Down Expand Up @@ -314,4 +313,22 @@ protected boolean areNotificationsEnabled(Context context) {
protected Activity getForegroundActivity() {
return ActivityStack.getInstance().getForegroundActivity();
}

/**
* Activity 是否可用
*/
protected boolean isActivityAvailable(Activity activity) {
if (activity == null) {
return false;
}

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

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

0 comments on commit 5864e2f

Please sign in to comment.