[TipToast]修正TipToast内存泄漏

This commit is contained in:
renwj
2022-02-24 15:11:39 +08:00
parent 60a8a73ec3
commit 4ffcbc977f
5 changed files with 100 additions and 11 deletions

View File

@@ -17,6 +17,13 @@ import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import com.mogo.eagle.core.utilcode.kotlin.ExtensionsKt;
import com.mogo.eagle.core.utilcode.mogo.logger.Logger;
@@ -34,7 +41,7 @@ public final class TipToast {
private static ToastViewGenerator sGenerator;
public static void init( Context context, ToastViewGenerator generator ) {
TipToast.sContext = context;
TipToast.sContext = context.getApplicationContext();
sHandler = new Handler( context.getMainLooper() );
sGenerator = generator;
}
@@ -165,20 +172,21 @@ public final class TipToast {
sHandler.post(() -> {
synchronized ( sSyncObject ) {
if ( context == null ) {
return;
}
if ( sToast != null ) {
sToast.cancel();
if ( sToast != null) {
View view = sToast.getView();
if (view != null && ViewCompat.isAttachedToWindow(view)) {
sToast.cancel();
}
}
if ( sGenerator == null ) {
sToast = Toast.makeText( context, msg, duration );
} else {
sToast = new Toast( context );
final View view = sGenerator.make( context, msg, tipDrawable );
if ( view != null ) {
sToast.setView( view );
sToast.setGravity( sGenerator.gravity(), sGenerator.xOffset(), sGenerator.yOffset() );
@@ -187,6 +195,15 @@ public final class TipToast {
sToast = Toast.makeText( context, msg, duration );
}
}
View view = sToast.getView();
if (view != null) {
LifecycleOwner lifecycleOwner = ExtensionsKt.getLifecycleOwner(view);
lifecycleOwner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
if (event == Lifecycle.Event.ON_DESTROY) {
sToast = null;
}
});
}
if ( sToast != null ) {
sToast.show();
}