AsyncTask 异步消息处理机制

来源:互联网 发布:python 字符串倒叙截取 编辑:程序博客网 时间:2024/04/27 09:14

        Android 提供了一个好用的工具---AsyncTask ,方便我们在子线程中对 UI 进行操作,AsyncTask 背后的实现原理也是基于异步消息处理机制的。下面是AsyncTask的一个小demo。


1、效果图:




2、activity_main.xml中的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:text="进度条"        android:textSize="50px" />    <ProgressBar        android:id="@+id/progressBar"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="match_parent"        android:layout_height="50pt"        android:layout_gravity="center"        android:max="100"        android:progress="0" />    <TextView        android:id="@+id/baifenbi"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:textSize="30px"        android:text="0" /></LinearLayout>

3、MainActivity.java中的代码:

package com.demo.asynctaskdemo;import android.app.Activity;import android.app.ActionBar;import android.app.Fragment;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;import android.os.Build;public class MainActivity extends Activity {private ProgressBar progress;private TextView baifenbi ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);progress = (ProgressBar) findViewById(R.id.progressBar);baifenbi = (TextView) findViewById(R.id.baifenbi) ;new MyTask().execute() ;}class MyTask extends AsyncTask<Void, Integer, Boolean> {private static final String TAG = "MyTask";/** * onPreExecute方法,在后台任务开始执行之前调用,用于进行一些界面上的初始化操作,比 如显示一个进度条对话框等。 */@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubToast.makeText(MyApplication.getContext(),"onPreExecute方法,界面上的初始化操作", 1).show();}/** * doInBackground方法,在子线程中运行,去处理所有的耗时任 务. 任务完成可以通过 return 语句来将任务的执行结果返回, * 如果 AsyncTask 的 第三个泛型参数指定的是 Void,就可以不返回任务执行结果。 @ 注意,在这个方法中是不 可以进行 UI * 操作的,如果需要更新 UI元素, 比如说反馈当前任务的执行进度,可以调 用 * publishProgress(Progress...)方法来完成。 */@Overrideprotected Boolean doInBackground(Void... params) {// TODO Auto-generated method stubLog.d(TAG, "--doInBackground" + params);int progress = 1;while (true) {try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}publishProgress(progress);if (progress >= 100) {progress = 0 ;break;}progress++ ;}return true;}/** * 在后台任务中调用了 publishProgress(Progress...)方法后,这个方法就会被调用, * 方法中携带的参数就是在后台任务中传递过来的。 在这个方法中可以对 UI 进行操作,利用参数中的数值就可以对界面元素进行相应地更新。 */@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubString text = "" ;if(values[0] == 100) {text = "下载完成" ;}else {text = values[0]+" %" ;}progress.setProgress(values[0]);baifenbi.setText(text);}/** * 后台任务执行完毕并通过 return 语句进行返回时,这个方法就会被调用。 * 返回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些 UI 操作, 比如说提醒任务执行的结果,以及关闭掉进度条对话框等。 */@Overrideprotected void onPostExecute(Boolean result) {// TODO Auto-generated method stubToast.makeText(MyApplication.getContext(), "进入onPostExecute方法", 1).show();}}}

4、MyApplication.java中的代码:
package com.demo.asynctaskdemo;import android.app.Application;import android.content.Context;public class MyApplication extends Application {private static Context context;@Overridepublic void onCreate() {context = getApplicationContext();}public static Context getContext() {return context;}}


5、AndroidManifest.xml中的代码:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.demo.asynctaskdemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="19" />    <application        android:name="com.demo.asynctaskdemo.MyApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.demo.asynctaskdemo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

项目下载:

AsyncTask异步消息处理机制 项目下载








0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 淘宝商品换主图被下架了怎么办 壁纸店没生意怎么办 支付宝不能借钱怎么办 淘宝号想注销怎么办 被陌生号码骚扰怎么办 买家辱骂卖家怎么办 淘宝禁止创建店铺怎么办 闲鱼上买东西被骗了怎么办 恶意买家付款了怎么办 换手机号了淘宝怎么办 旺旺发不了图片怎么办 拼多多买家投诉怎么办 拼多多恶意用户怎么办 淘宝运单号填错了怎么办 淘宝退货卖家不处理怎么办 淘宝长时间不发货怎么办 实体店卖假货怎么办 淘宝店暂停服务怎么办 淘宝直播开始没人怎么办 店铺违规虚假交易怎么办 电视无频道信息怎么办 hdp直播频道丢失怎么办 小红书订单删了怎么办 退款售后删除我怎么办 毛衣袖子肥了怎么办 店面生意不好要怎么办 中国的农民以后怎么办 做到不好的梦怎么办 美瞳线眼睛肿了怎么办 淘宝买家限购怎么办 一楼房屋潮湿怎么办 一楼屋子潮湿怎么办 淘宝店铺销量不好怎么办 淘宝发不了驿站怎么办 羊水指数过少怎么办 孕妇吃了凉果类怎么办 衣服腰围小了怎么办 网上买东西被骗了怎么办 拼多多排名下降怎么办 买家好评率0怎么办 淘宝组合形式少怎么办