Android AsyncTask 异步任务操作
16lz
2021-01-23
1:activity_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/tvInfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <ProgressBar android:layout_below="@id/tvInfo" android:id="@+id/asyncPb" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone" /> </RelativeLayout>
2:MainActivity.java
package com.example.async;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.ProgressBar;import android.widget.TextView;import android.app.Activity;public class MainActivity extends Activity { private ProgressBar asyncPb = null; private TextView tvInfo = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvInfo = (TextView)findViewById(R.id.tvInfo); String params = "Welcome to here"; new MyAsyncTask().execute(params); } private class MyAsyncTask extends AsyncTask<String, Integer, String>{ @Override protected void onPreExecute() { //做一些预处理 asyncPb = (ProgressBar)findViewById(R.id.asyncPb); asyncPb.setVisibility(View.VISIBLE); } @Override protected String doInBackground(String... params) { //执行耗时操作,网络任务、文件操作、数据库操作、复杂计算操作 int myProgress = 0; int length = params[0].length(); for(int i=1; i<=length; i++){ myProgress = i; //模拟耗时操作 try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } publishProgress((int)((myProgress/(float)length)*100)); } //它将传递给onPostExecute return params[0]; } @Override protected void onProgressUpdate(Integer... values) { //更新进度条 asyncPb.setProgress(values[0]); tvInfo.setText("已加载:"+(values[0])+"%"); } @Override protected void onPostExecute(String result) { //更新UI tvInfo.setText("加载完成:"+result); } }}
更多相关文章
- android > 旋转屏幕时 不重加载 activity
- android中的spinner动态加载内容
- 图片压缩保存读取操作
- Android 数据库操作 创建 添加 删除 查询
- android gallery相关操作
- Android中高效的显示图片之一 ——加载大图
- HelloWorld-----Google手机操作系统Android应用开发入门
- Android:Activity(五):Activity加载模式
- Android动态加载入门 简单加载模式