Timer 的用法
Timer要和TimerTasker一起使用,Timer设置了执行的时间和周期,TimerTasker创建线程执行具体的任务.
启动Timer
Timer timer = new Timer();
TimerTasker timerTask = new TimerTask()
{
@Override
public void run()
{
//被周期性执行的任务
}
};
// 启动任务 ,延时1秒,每1秒执行一次task的run方法
timer.schedule(timerTask, 1000, 1000);
结束任务
if (timer != null)
{
timerTask.cancel();
timer.cancel();
timerTask = null;
timer = null;
}
一般来说我在onResume时让Timer重新启动,而在onPause时让Timer终止.
PorgressBar 有两种,圆形和条形
圆形没有进度值,就一直转
条形的有最大值和进度值
当然原型的有大中小三种风格,条形的有水平和垂直两种风格
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/progressBar2"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/progressBar3"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
条形的控制:
首先要设置最大值
bar3.setMax(100);
其次根据实际进度设置值
bar3.setProgress(progress);
package com.example.l01uicontrols;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.ProgressBar;
public class UsingProgressBar extends Activity
{
@Override
protected void onPause()
{
stopTimer();
super.onPause();
}
@Override
protected void onResume()
{
startTimer();
super.onResume();
}
private ProgressBar bar1, bar2, bar3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.using_progress_bar);
bar3 = (ProgressBar) findViewById(R.id.progressBar3);
bar3.setMax(100);
}
private Timer timer = null;
private TimerTask timerTask = null;
public void startTimer()
{
if (timer == null)
{
timer = new Timer();
timerTask = new TimerTask()
{
private int progress = 0;
@Override
public void run()
{
if (progress != 100)
{
progress += 10;
bar3.setProgress(progress);
}
else
{
stopTimer();
}
}
};
// 启动任务 ,延时1秒,每1秒执行一次task的run方法
timer.schedule(timerTask, 1000, 1000);
}
}
public void stopTimer()
{
if (timer != null)
{
timerTask.cancel();
timer.cancel();
timerTask = null;
timer = null;
}
}
}