在单独的类文件中使用AsyncTask

在单独的类文件中使用AsyncTask

本文介绍了Android开发:在单独的类文件中使用AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩各种试图熟悉AsyncTask的例子。到目前为止,我看到的所有示例都将AsyncTask包含在主要活动的onCreate方法中。我不太喜欢,所以我想看看将它分成自己的课程有多难。到目前为止我有这个:

I have been playing around with various examples trying to familiarize myself with AsyncTask. So far all the examples I have seen have had the AsyncTask included into the onCreate method of the main activity. Which I don't like very much, so I was wanting to see how hard it would be to separate it into its own class. So far I have this:

主要活动

package com.example.asynctaskactivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asynctaskactivity.ShowDialogAsyncTask;

public class AsyncTaskActivity extends Activity {

 Button btn_start;
 ProgressBar progressBar;
 TextView txt_percentage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_start = (Button) findViewById(R.id.btn_start);
        progressBar =  (ProgressBar) findViewById(R.id.progress);
        txt_percentage= (TextView) findViewById(R.id.txt_percentage);
        Log.v("onCreate","Attempt set up button OnClickListener");
        btn_start.setOnClickListener(new View.OnClickListener()
        {
           @Override
           public void onClick(View v) {
               btn_start.setEnabled(false);
               new ShowDialogAsyncTask().execute();
           }
        });

        Log.v("onCreate","Success!");
    }
}

新的单独 AsyncTask类

package com.example.asynctaskactivity;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void>{
int progress_status;

@Override
    protected void onPreExecute() {
    // update the UI immediately after the task is executed
    Log.v("onPreExecute","1");
    super.onPreExecute();
    Log.v("onPreExecute","2");
    //Toast.makeText(AsyncTaskActivity.this,"Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
    progress_status = 0;
    Log.v("onPreExecute","3");
    txt_percentage.setText("downloading 0%");
    Log.v("onPreExecute","4");
    }

    @Override
    protected Void doInBackground(Void... params) {
        Log.v("doInBackground","1");
        while(progress_status<100){

            progress_status += 2;

            publishProgress(progress_status);
            SystemClock.sleep(300);

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);

    progressBar.setProgress(values[0]);
    txt_percentage.setText("downloading " +values[0]+"%");
    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    //Toast.makeText(AsyncTaskActivity.this,"Invoke onPostExecute()", Toast.LENGTH_SHORT).show();

    txt_percentage.setText("download complete");
    btn_start.setEnabled(true);
    }
}

最初这是所有主要活动,因此提到了asynctask理论上应该更新的元素。显然目前这会导致运行时错误,然后让我思考。如何让文件分离,但仍然更新UI线程。

Originally this was all in the main activity, hence the mentions to the elements that the asynctask should in theory update. Obviously at present this is causing runtime errors, which then got me thinking. How can I have the file seperate but still update the UI thread.

很抱歉,如果这是一个愚蠢的问题,特别是Android开发和后台线程的新功能。

Sorry if this is a stupid question, quite new to android development and background threads in particular.

推荐答案

Okey。首先,您知道在Activity中添加的 AsyncTask 的主要优点是您可以直接访问所有UI元素,并且可以实现非常轻量级的UI更新。

Okey. So at first you know that main advantage of AsyncTask added in Activity as inner class is that you have direct access to all UI elements and it makes possible pretty "lightweight" UI updates.

但是如果你决定将AsyncTask与Activity分开(这也有一些好处,eq代码更干净,app逻辑与外观分离),你可以:

But if you decided to make AsyncTask separated from Activity(which also have some benefits e.q. code is more clean and app logic is separated from appearance) class you can:


  • 您可以通过类的构造函数传递UI元素

  • 您可以创建各种setter

  • 您可以创建一些可以保存回调的界面。查看

  • You can pass UI elements via constructor of class
  • You can create various setters
  • You can create some interface that will hold callbacks. Look at Android AsyncTask sending Callbacks to UI

这就是我想要的所有内容。

This is all what you need i guess.

这篇关于Android开发:在单独的类文件中使用AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:47