LifecycleObserver解耦Activity和组件

LifecycleObserver解耦Activity和组件,第1张

LifecycleObserver解耦Activity和组件

实现一个监视看手机时长的应用
自定义MyChronometer

package com.example.jetpack;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import java.util.Observer;

public class MyChronometer extends Chronometer implements LifecycleObserver {
    long pauseTime;
    public MyChronometer(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @onLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onStart(){
        setbase(SystemClock.elapsedRealtime()-pauseTime);
        start();
    }
    @onLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onStop(){
        pauseTime=SystemClock.elapsedRealtime()-getbase();
        stop();
    }
}

添加lifecycle监听

//        不要忘记add生命周期监听,否则lifecycle无效
        getLifecycle().addObserver(chronometer);
package com.example.jetpack;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;

import androidx.appcompat.app.AppCompatActivity;

public class MainLifeCycleActivity extends AppCompatActivity {
    private MyChronometer chronometer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer = (MyChronometer) findViewById(R.id.chronometer);
//        不要忘记add生命周期监听,否则lifecycle无效
        getLifecycle().addObserver(chronometer);

    }


}



    


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5684111.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存