feat:DoricPanel observe lifecycle

This commit is contained in:
pengfei.zhou 2019-11-23 11:40:45 +08:00
parent a3f1e67db3
commit b475097c34
2 changed files with 35 additions and 10 deletions

View File

@ -70,7 +70,6 @@ public class DemoActivity extends AppCompatActivity {
});
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();

View File

@ -16,11 +16,13 @@
package pub.doric;
import android.content.Context;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import android.util.AttributeSet;
import android.widget.FrameLayout;
@ -32,26 +34,25 @@ import pub.doric.utils.DoricUtils;
* @Author: pengfei.zhou
* @CreateDate: 2019-07-18
*/
public class DoricPanel extends FrameLayout {
public class DoricPanel extends FrameLayout implements LifecycleObserver {
private DoricContext mDoricContext;
public DoricPanel(@NonNull Context context) {
super(context);
this(context, null);
}
public DoricPanel(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this(context, attrs, 0);
}
public DoricPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (getContext() instanceof LifecycleOwner) {
((LifecycleOwner) getContext()).getLifecycle().addObserver(this);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public DoricPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void config(String script, String alias) {
DoricContext doricContext = DoricContext.create(getContext(), script, alias);
@ -64,6 +65,10 @@ public class DoricPanel extends FrameLayout {
if (getMeasuredState() != 0) {
mDoricContext.init(DoricUtils.px2dp(getMeasuredWidth()), DoricUtils.px2dp(getMeasuredHeight()));
}
if (getContext() instanceof LifecycleOwner
&& ((LifecycleOwner) getContext()).getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
mDoricContext.onShow();
}
}
@Override
@ -84,4 +89,25 @@ public class DoricPanel extends FrameLayout {
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onActivityResume() {
if (mDoricContext != null) {
mDoricContext.onShow();
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onActivityPause() {
if (mDoricContext != null) {
mDoricContext.onHidden();
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onActivityDestroy() {
if (mDoricContext != null) {
mDoricContext.teardown();
}
}
}