Android开发: AsyncTask 任务屏幕旋转处理 ProgressDialog的方法

今天重新研究了一下AsyncTask这个后台任务的代码,发现旋转设备时,ProgressDialog会自动消失,但是后台的工作线程依然在运行中,大大的降低了用户体验;

书里有说使用弱引用,但是百度了很多帖子,看到的都死废话连篇,或者是我看不懂吧,最后发现一个帖子,只要在Manifest.xml中配置一个参数就可以实现ProgressDialog不被隐藏,以下Manifest.xml的代码,红色字体为关键:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="screenSize|orientation"
    android:theme="@style/AppTheme.NoActionBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

大致意思应该是,在配置被改变的时候自动执行UI更新吧。

现在贴出AsyncTask的代码:

package com.lanxin.testasynctask;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by Alan on 2016/6/3 0003.
 */
public class AsyncTaskEx extends AsyncTask<String,Integer,Object> implements DialogInterface.OnCancelListener {

    private static final String TAG = "AsyncTaskEx";
    private Context mContext;
    private ProgressDialog pd;
    private boolean Indeterminate;
    WeakReference<ProgressDialog> wr = null;

    public AsyncTaskEx(Context ctx,boolean isIndeterminate){
        mContext = ctx;
        Indeterminate = isIndeterminate;
    }

    /**
     * 开始执行
     */
    protected void onPreExecute() {
        Log.i(TAG,"onPreExecute");
        pd = new ProgressDialog(mContext);
        pd.setIndeterminate(Indeterminate);
        pd.setCanceledOnTouchOutside(false);
        if(!Indeterminate)
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        pd.setCancelable(true);
        pd.setOnCancelListener(this);
        pd.setMessage("onPreExecute....0%");
        pd.setTitle("AsyncTaskEx");
        pd.setMax(100);
        //pd.setProgress(0);
        pd.show();

    }

    /**
     * 进度更新
     * @param values 进度值 整数
     */
    protected void onProgressUpdate(Integer... values) {
        Log.i(TAG, "onProgressUpdate:" + values[0]);

        pd.setProgress(values[0]);
        pd.setMessage("onPreExecute...." + values[0] + "%");
    }

    protected void onPostExecute(Object result) {
        Log.i(TAG,"onPostExecute:"+result.toString());
        pd.cancel();
    }

    @Override
    protected Object doInBackground(String... params) {
        for (int i = 0; i < 100; i++){
            publishProgress(i);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return new String("ok");
    }


    @Override
    public void onCancel(DialogInterface dialog) {
        this.cancel(true);
        Log.i(TAG,"cancel");
    }
}

写给自己看的,请不要喷我。

Leave a Comment