这里介绍一个新的异步处理的方法,这个方法要比较简单一点,那就来看一段代码:
1、先写一个XML文件,里面写一个点击按钮,和一个进度条(SeekBar):
<span style="font-size:18px;"><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"
>
<Button
android:id="@+id/asynctaskbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击下载" />
<SeekBar
android:id="@+id/seekbarbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
</LinearLayout></span>
2、再写一个Activty继承Activty,实例化控件:
<span style="font-size:18px;">package com.example.com.scxh.asynctask.yibu;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends Activity {
public static Button mButton;
private MyAsyncTask mmyAsyncTask;
public static SeekBar mSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton=(Button) findViewById(R.id.asynctaskbtn);
mSeekBar=(SeekBar) findViewById(R.id.seekbarbtn);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mmyAsyncTask=new MyAsyncTask();
mmyAsyncTask.execute("http://www.scxh.download/file1.jpg","http://www.scxh.download/file1.jpg");
}
});
}
}
</span>
3、在写一个Asynctask继承Asynctask
package com.example.com.scxh.asynctask.yibu;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.SeekBar;
public class MyAsyncTask extends AsyncTask<String, Integer, String> {
private MyAsyncTask mmyAsyncTask;
private int count = 0;
protected void onPreExecute() {
super.onPreExecute();
Log.v("onPreExecute", "onPreExecute..............");
}
//实现AsyncTask的方法
@Override
protected String doInBackground(String... params) {
String file1 = params[0];
String file2 = params[1];
//写一个线程
while (count < 100) {
count++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
publishProgress(count);
}
return "下载成功";
}
//这个方法就是把进度条和按钮联系起来
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
MainActivity.mSeekBar.setProgress(values[0]);
if(values[0]==99){
//进度条跑完后按钮变为“下载完成”
MainActivity.mButton.setText("下载完成");
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
2和3最好写在一个Activty里面,
这里我是分开写的