Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android AsyncTask 異步運用

Android AsyncTask 異步運用

編輯:關於Android編程

package com.example.hand;


import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class MainActivity extends
Activity {


ProgressDialog progressDialog;
TextView mTextView;


@Override
public void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView1);
findViewById(R.id.button1)
.setOnClickListener(
new OnClickListener() {


public void onClick(
View v) {
// TODO Auto-generated method stub


@SuppressWarnings("unused")
LoadTask loadtask = new LoadTask();


loadtask.execute();
}
});
}


public class LoadTask
extends
AsyncTask<Void, Integer, String> {


private ProgressDialog progressDialog;


@Override
protected String doInBackground(
Void... params) {
// TODO Auto-generated method stub


int sum = 1;
while (sum <= 10) {
try {
Thread.sleep(500);
publishProgress(sum);
sum++;
}
catch (Exception e) {
// TODO: handle exception
}
}
return "Loading Finished";
}


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog
.show(MainActivity.this,
"demo",
"loading......",
true);
}


@Override
protected void onPostExecute(
String result) {
// TODO Auto-generated method stub
progressDialog.dismiss();
mTextView.setText(result);
}


@Override
protected void onProgressUpdate(
Integer... values) {
// TODO Auto-generated method stub
mTextView.setText(values[0]
* 10 + "%");
}
}


public boolean onCreateOptionsMenu(
Menu menu) {
getMenuInflater().inflate(
R.menu.activity_main,
menu);
return true;
}
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved