【问题标题】:What is the way to run a new thread and a UI thread in Android? [closed]Android中运行新线程和UI线程的方法是什么? [关闭]
【发布时间】:2013-04-18 19:18:50
【问题描述】:

据我所知,当我们在 android 中运行进程时,它们从主线程开始。当我们做一些较重的工作时,我们会使用一个新线程。如果我们想修改 UI 外观,我们会使用 run on UI。

谁能向我解释一下这些线程的作用以及它们是如何使用的?

【问题讨论】:

    标签: java android multithreading


    【解决方案1】:

    我会研究以下两件事:

    HandlerAsyncTask

    这是一个非常好的 Android 线程资源。 http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

    另外,如果您因为要获取一些数据/进行简单的 API 调用而询问,我绝对建议您查看http://loopj.com/android-async-http/。这将使您的生活变得更加简单。

    【讨论】:

    • 这个,AsyncTask 会让你的生活轻松很多。
    • 请注意,这些线程的运行时间不应超过几秒钟!
    【解决方案2】:

    主要的ThreadUI Thread。因此,当您启动Activity 时,您就在Main (UI) Thread 上。当您想使用单独的线程来执行“繁重的工作”(例如网络进程)时,您有多种选择。您可以在您的Activity 中创建一个单独的Thread 并调用runOnUiThread 来更新您的UI。您还可以使用 AsyncTask 进行短期操作。根据文档,可能只需要几秒钟的时间。这是一个简短的例子:

    public class TalkToServer extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    
    }
    
    @Override
    protected String doInBackground(String... params) {
    //do your work here
        return something;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
           // do something with data here-display it or send to mainactivity
    

    你会调用它

    TalkToServer myAsync = new TalkToServer() //can add params if you have a constructor  
    myAsync.execute() //can pass params here for `doInBackground()` method
    

    请确保不要尝试在doInBackground() 方法中更新UI。使用任何其他方法或将数据传递回Activity 方法。如果你的AsyncTask 类是Activity 的内部方法,那么你可以使用它的context 来更新UI。如果它在自己的文件中,那么您需要将context 传递给它的构造函数,例如

    TalkToServer myAsync = new TalkToServer(this);
    

    您可能还想阅读这篇文章

    Painless Threading

    【讨论】:

      【解决方案3】:

      UI 线程和主线程只是同一个线程的不同名称。

      应用程序的所有 UI 膨胀都在这个主线程上完成。我们将“较重”的工作委托给其他线程的原因是因为我们不希望这些操作减慢 UI 的响应速度和膨胀时间。

      您将希望在主线程上运行任何更改 UI 或修改 UI 使用的对象的操作。

      AsyncTask 示例

      package com.wolfdev.warriormail;
      
      import android.app.Activity;
      import android.content.Intent;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.view.animation.Animation;
      import android.view.animation.AnimationUtils;
      import android.widget.Button;
      import android.widget.CheckBox;
      import android.widget.EditText;
      
      public class LoginActivity extends Activity implements OnClickListener{
          private Button loginButton;
          private EditText eText;
          private EditText pText;
          private CheckBox box;
          private String user; 
          private String pass;
      
          @Override
          public void onCreate(Bundle savedInstanceState){
              super.onCreate(savedInstanceState);
              setContentView(R.layout.login);
      
                  //Initialize UI objects on main thread
              loginButton = (Button) findViewById(R.id.button1);
              loginButton.setOnClickListener(this);
              eText = (EditText) findViewById(R.id.editText1);
              pText = (EditText) findViewById(R.id.editText2);
              eText.clearFocus();
              pText.clearFocus();
              Animation fadeIn = AnimationUtils.loadAnimation(this,R.anim.fadeanimation);
              Animation slideIn = AnimationUtils.loadAnimation(this, R.anim.slideanimation);
              eText.startAnimation(slideIn);
              pText.startAnimation(slideIn);
              box = (CheckBox)findViewById(R.id.checkBox1);
              box.startAnimation(fadeIn);
              login.startAnimation(fadeIn);
          }
      
          @Override
          public void onClick(View v) {
              user = email.getText().toString();
              password = pass.getText().toString();
      
          }
      
          class LoginTask extends AsyncTask<Void,Void,Void>{
                  @Override
                  protected Void doInBackground(Void... args){
                          /* Here is where you would do a heavy operation
                          *  In this case, I want to validate a users
                          *  credentials.  If I would do this on the main
                          *  thread, it would freeze the UI.  Also since
                          *  this is networking, I am forced to do this on
                          *  a different thread.
                          */
      
                          return null;
                  }
      
                  @Override
                  protected void onPostExecute(Void result){
                           /* This function actually runs on the main
                           * thread, so here I notify the user if the
                           * login was successful or if it failed.  If
                           * you want update the UI while in the background
                           * or from another thread completely, you need to
                           * use a handler.
                           */
                  }
          }
      }
      

      【讨论】:

      • 理论上我理解它,但是我想看一些例子。您能否从您的代码中提供一些内容。就像代码一样,您将在主线程上执行某些操作,然后在另一个线程上执行某些操作,然后返回并编辑 UI。谢谢
      • 感谢您的回答
      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2011-04-16
      • 2012-04-12
      • 1970-01-01
      相关资源
      最近更新 更多