android应用开发之AsyncTask

本文介绍如何使用 AsyncTask 在 Android 中实现耗时操作,并通过按钮点击触发该操作,同时展示了操作过程中的状态更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值