实现一个监视看手机时长的应用
自定义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); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)