android应用开发之AsyncTask

来源:互联网 发布:南极洲有多大 知乎 编辑:程序博客网 时间:2024/06/16 08:54

AsyncTaskActivity.java

package cn.sanbo.test;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;import android.widget.Toast;public class AsyncTaskActivity extends Activity implements OnClickListener {private TextView textView;private boolean isExits = false;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);init();}private void init() {this.findViewById(R.id.btnAsync).setOnClickListener(this);textView = (TextView) this.findViewById(R.id.tv_text);}public void onClick(View v) {if (v.getId() == R.id.btnAsync) {if (!isExits) {isExits = true;new MyAsyncTask().execute(null);} else {Toast.makeText(AsyncTaskActivity.this, "耗时操作中~", 0).show();}}}class MyAsyncTask extends AsyncTask {protected Object doInBackground(Object... params) {boolean isGoOn = true ;int jd = 0;while (isGoOn){try {jd++;Thread.sleep(30);if (jd == 100) {isGoOn = false;}} catch (Exception e) {e.printStackTrace();}}return null;}protected void onPostExecute(Object result) {super.onPostExecute(result);textView.setText("耗时操作中~" );}protected void onPreExecute() {super.onPreExecute();isExits = false ;textView.setText("耗时完成!");}}}

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" >    <Button        android:id="@+id/btnAsync"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="AsyncTask" />    <TextView        android:id="@+id/tv_text"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:text="下载~"        android:textColor="@android:color/white"        android:textSize="20sp" /></LinearLayout>




原创粉丝点击