在Async Task中启动新线程

时间:2021-10-21 20:43:53

Is it possible start a new thread within an Async task? Something like this:

是否可以在异步任务中启动新线程?像这样的东西:

public class FirstActivity extends Activity {

protected ProgressBar progBar;
protected Intent intent;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    progBar = (ProgressBar)findViewById(R.id.start_progressBar);
    progBar.setProgress(0);
    new StartingApp().execute();
}

protected class StartingApp extends AsyncTask<Void, Integer, Void> {

    int myProgress;

    @Override
    protected void onPreExecute() {
        myProgress = 0;
    }

    @Override
    protected Void doInBackground(Void... params) {

        while(myProgress<50){
            myProgress++;
            publishProgress(myProgress);
                SystemClock.sleep(10);
            }

        MyRunnableClass mrc = new MyRunnableClass();
        mrc.run();

        return null;    
    }

    @Override
    protected void onPostExecute(Void result){

        intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
    }

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

        progBar.setProgress(values[0]);
    }
}
}

MyRunnableClass is a class which implements Runnable. I want something like this because in the first activity I want to show a progress bar while the application is initializing (fill data structures, starting threads).

MyRunnableClass是一个实现Runnable的类。我想要这样的东西,因为在第一个活动中我想在应用程序初始化时显示进度条(填充数据结构,启动线程)。

Another question I have is: should I use the run() or start() method?

我的另一个问题是:我应该使用run()或start()方法吗?

Thanks in advance!

提前致谢!

1 个解决方案

#1


0  

Why do you want to do that? As pointed out in the code you need to call new Thread(mrc).start() to make it work. Otherwise i dont see any problem in that code spawning a new thread.

你为什么要那样做?正如在代码中指出的那样,您需要调用新的Thread(mrc).start()来使其工作。否则我没有看到产生新线程的代码有任何问题。

#1


0  

Why do you want to do that? As pointed out in the code you need to call new Thread(mrc).start() to make it work. Otherwise i dont see any problem in that code spawning a new thread.

你为什么要那样做?正如在代码中指出的那样,您需要调用新的Thread(mrc).start()来使其工作。否则我没有看到产生新线程的代码有任何问题。