实现一个监视看手机时长的应用 自定义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);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.jetpack.MyChronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
|