activity_directpage代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="@drawable/face">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:textSize="20sp" />
</RelativeLayout>
</LinearLayout>
directpage代码:
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class directpage extends AppCompatActivity implements View.OnClickListener {
private int recLen = 5;
private TextView tv;
Timer timer = new Timer();
private Handler handler;
private Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, flag);
setContentView(R.layout.activity_directpage);
initView();
timer.schedule(task, 1000, 1000);
handler = new Handler();
handler.postDelayed(runnable = new Runnable() {
@Override
public void run() {
Intent intent = new Intent(directpage.this, login.class);
startActivity(intent);
finish();
}
}, 5000);
}
private void initView() {
tv = findViewById(R.id.tv);
tv.setOnClickListener(this);
}
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
recLen--;
tv.setText("跳过 " + recLen);
if (recLen < 0) {
timer.cancel();
tv.setVisibility(View.GONE);
}
}
});
}
};
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv:
Intent intent = new Intent(directpage.this, login.class);
startActivity(intent);
finish();
if (runnable != null) {
handler.removeCallbacks(runnable);
}
break;
default:
break;
}
}
}
- 应该通过配合Handler来实现timer功能的。
- Timer和TimerTask在调用cancel()取消后不能再执行schedule语句。只能在Ui主线程中更新控件/组件。在其他线程中,更新控件/组件会报错。
3.方法postDelayed的作用是延迟多少毫秒后开始运行。
4.removeCallbacks方法是删除指定的Runnable对象,使线程对象停止运行,这个方法使用的前提是之前调用过sendEmptyMessageDelayed(0, time),意思是延迟time执行handler中msg.what=0的方法;在延迟时间未到的前提下,执行removeMessages(0),则上面的handler中msg.what=0的方法取消执行;在延迟时间已到,handler中msg.what=0的方法已执行,再执行removeMessages(0),不起作用。 - runOnUIthread(Runnale)和Handler.post(Runnable)都是将更新UI的操作提交到主线程/UI线程中执行。