说明:最近碰到一个需求,根据后端返回的倒计时时间,展示一个定时器,要求页面切换和刷新的时候,定时器保持运行,
step1:
package com.unayshah.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class HomeActivity extends AppCompatActivity {
private EditText et_home;
private Button btn_start;
private TextView tv_home;
private String etString;
private int etInt=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_home = findViewById(R.id.et_home);
btn_start = findViewById(R.id.btn_start);
tv_home = findViewById(R.id.tv_home);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
etString = et_home.getText().toString();
etInt= Integer.parseInt(etString);
mScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
etInt--;
try {
Message msg = new Message();
msg.what = 402;
msg.obj =etInt;
mHandler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 1, 1, TimeUnit.SECONDS);
}
});
}
private ScheduledExecutorService mScheduledExecutorService = Executors.newScheduledThreadPool(0, new ThreadFactory() {
@Override
public Thread newThread(@NonNull Runnable r) {
return new Thread(r) {
@Override
public void run() {
Log.e("lzp", "newThread");
super.run();
Log.e("lzp", "newThread over");
}
};
}
});
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
if (message.what == 402) {
int post = (int) message.obj;
Log.e("lzp", "newThread"+post);
if (post<1){
tv_home.setVisibility(View.INVISIBLE);
}else{
tv_home.setVisibility(View.VISIBLE);
}
tv_home.setText(String.valueOf(post));
}
return false;
}
});
@Override
protected void onDestroy() {
super.onDestroy();
Log.e("lzp", "onDestroy注销:");
//mScheduledExecutorService.shutdown(); 这一句可以结束定时循环任务
}
}