我正在阅读有关AsyncTask的文章,并尝试了下面的简单程序。但这似乎并不奏效。我该怎么做呢?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
我只是试图在后台进程中5秒后更改标签。
这是我的main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="10dip">
</ProgressBar>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Progress" >
</Button>
<TextView android:id="@+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace"/>
</LinearLayout>
private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Do code here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
Toast toast = Toast.makeText(
getActivity(),
"An error is occurred due to some problem",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
这里的概念和代码
我已经创建了一个简单的例子使用AsyncTask的Android。它从onPreExecute(), doInBackground(), publishProgress()开始,最后是onProgressUpdate()。
在这种情况下,doInBackground()作为后台线程工作,而其他线程在UI线程中工作。你不能访问doInBackground()中的UI元素。顺序和我之前提到的一样。
然而,如果你需要从doInBackground更新任何小部件,你可以从doInBackground发布进度,它会调用onProgressUpdate来更新你的UI小部件。
class TestAsync extends AsyncTask<Void, Integer, String> {
String TAG = getClass().getSimpleName();
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG + " PreExceute","On pre Exceute......");
}
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
for (int i=0; i<10; i++){
Integer in = new Integer(i);
publishProgress(i);
}
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a) {
super.onProgressUpdate(a);
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(TAG + " onPostExecute", "" + result);
}
}
在你的活动中这样称呼它:
new TestAsync().execute();
开发人员参考资料
如果你打开AsyncTask类,你可以看到下面的代码。
public abstract class AsyncTask<Params, Progress, Result> {
@WorkerThread
protected abstract Result doInBackground(Params... params);
@MainThread
protected void onPreExecute() {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
}
AsyncTask的特性
AsyncTask是一个抽象类
AsyncTask有3个泛型参数。
AsyncTask有doInBackground onPreExecute onPostExecute的抽象方法
doInBackground是WorkerThread(你不能更新UI)
onPreExecute是主线程
onPostExecute是主线程(你可以更新UI)
例子
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
AsyncTask<Void, Void, Post> asyncTask = new AsyncTask<Void, Void, Post>() {
@Override
protected Post doInBackground(Void... params) {
try {
ApiClient defaultClient = Configuration.getDefaultApiClient();
String authorization = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1ODIxMzM4MTB9.bA3Byc_SuB6jzqUGAY4Pyt4oBNg0VfDRctZ8-PcPlYg"; // String | JWT token for Authorization
ApiKeyAuth Bearer = (ApiKeyAuth) defaultClient.getAuthentication("Bearer");
Bearer.setApiKey(authorization);
PostApi apiInstance = new PostApi();
String id = "1"; // String | id
Integer commentPage = 1; // Integer | Page number for Comment
Integer commentPer = 10; // Integer | Per page number For Comment
Post result;
try {
result = apiInstance.apiV1PostsIdGet(id, authorization, commentPage, commentPer);
} catch (ApiException e) {
e.printStackTrace();
result = new Post();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return new Post();
}
}
@Override
protected void onPostExecute(Post post) {
super.onPostExecute(post);
if (post != null) {
mEmailView.setText(post.getBody());
System.out.print(post);
}
}
};
asyncTask.execute();
}
在使用AsyncTask时,有必要创建一个类继任者,并在其中注册我们所需的方法的实现。本节课我们将学习三种方法:
doInBackground -将在一个新线程中执行,在这里我们解决了所有困难的任务。因为非主线程不能访问UI。
onPreExecute -在doInBackground之前执行,并可以访问UI
onPostExecute -在doInBackground之后执行(如果AsyncTask被取消就不工作-关于这个在下一课中),并可以访问UI。
这是MyAsyncTask类:
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Start");
}
@Override
protected Void doInBackground(Void... params) {
// Your background method
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tvInfo.setText("Finish");
}
}
这是如何调用你的Activity或Fragment:
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
如何记住AsyncTask中使用的参数?
不
如果你是AsyncTask的新手,那么在编写AsyncTask时很容易感到困惑。主要原因是AsyncTask中使用的参数,即AsyncTask<A, B, C>。基于方法的A, B, C(参数)签名的不同,这使得事情更加混乱。
保持简单!
关键是不要死记硬背。如果你可以想象你的任务真正需要做什么,那么在第一次尝试时用正确的签名编写AsyncTask将是小菜一碟。只要弄清楚你的输入、进度和输出是什么,你就可以开始了。
什么是AsyncTask?
AsyncTask是一个运行在后台线程的后台任务。它接受一个Input,执行Progress并给出一个Output。
例如,AsyncTask<Input, Progress, Output>。
例如:
与方法的关系是什么?
在AsyncTask和doInBackground()之间
doInBackground()和onPostExecute(),onProgressUpdate() '也是
相关的
怎么写在代码里?
DownloadTask extends AsyncTask<String, Integer, String>{
// Always same signature
@Override
public void onPreExecute()
{}
@Override
public String doInbackGround(String... parameters)
{
// Download code
int downloadPerc = // Calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... parameters)
{
// Show in spinner, and access UI elements
}
}
您将如何运行此任务?
new DownLoadTask().execute("Paradise.mp3");