本篇小案例,完成一个倒计时。方式选择AsyncTask。代码贴在下面:
布局文件soeasy:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:textSize="18sp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="32dp" />
<Button
android:text="开始任务"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="start"/>
</LinearLayout>
接着活动代码:
package com.example.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
}
public void start(View v) {
//@1:对应的参数是:1、doInBackground回调中的传入的参数类型;2、执行任务的参数类型
//@2:进度参数,与进度有关。onProgressUpdate的参数类型
//@3:1、doInBackground的返回值类型;2、执行结果onPostExecute传入的参数类型
new AsyncTask<Integer, Integer, Integer>() {
@Override
protected void onPreExecute() {
// 准备执行前调用,用于界面初始化操作
}
@Override
protected Integer doInBackground(Integer... params) {
// 子线程,耗时操作
int start = params[0];
int end = params[1];
int result = 0;
for (int i = end; i >= start; i--) {
SystemClock.sleep(20);
result = i;
publishProgress(result);//把进度推出去,推给onProgressUpdate参数位置
}
return result;
}
@Override
protected void onProgressUpdate(Integer[] values) {
//主线程执行的回调,可更新进度。values为doInBackground调用publishProgress时候推过来的参数。这里每次推一个。因此数组长度就是0
int progress = values[0];
tv.setText(progress+"");
};
@Override
protected void onPostExecute(Integer result) {
// 执行完成的回调,即获得数据后的回调
tv.setText(result+"");
}
}.execute(0,100);
}
}
对于AsyncTask的详细分析,请关注《Android进阶》专栏介绍。上面的代码注释也很清晰,运行看看效果:
欢迎关注本博客,不定期推送简单有趣的小文哦。