在执行线程

时间:2015-12-09 08:18:22

标签: java android

在我的应用程序中,我正在运行一个执行某些文本文件操作的线程。在此期间,我还想继续使用setText在UI上更新结果。请建议一个方法。

testThread = new Thread(){
          public void run()
          {
            Log.i("TestApp","Test Thread Running");
            runTest();

          }

        };

据我所知,在UI线程上执行耗时的操作以避免ANR并不好。请建议我可以同时做两件事的方式。

4 个答案:

答案 0 :(得分:1)

不是使用AsyncTask,而是更好,这是一个样本

class GetStuffAsyncly extends AsyncTask<String, String, String> {
   //What ever variables, you needed



    @Override
    protected String doInBackground(String... args) {
        // do stuff in background...
        //When you want to update something in the middle use the below method
        publishProgress(Value);    
        return args[0];
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String jsonString) {
       //Here the thread execution ends.

    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
       //Here you will get the value what you want to update while running the thread.
    }
}

要运行它,您可以使用

new GetStuffAsyncly().execute();

答案 1 :(得分:1)

试试这个:

  private void runThread() {

    new Thread() {
        public void run() {
            while (i++ < 1000) {
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                           //Do something on your UI
                        }
                    });
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

答案 2 :(得分:0)

有几种方法。一种常见的模式是使用AsyncTask,但如果您需要进行多次中间进度更新,则AsyncTask最适合每个步骤相似的步骤(例如下载文件并相应地为每个下载的x kB更新UI)。但是对于很多情况来说这没问题。

如果您的任务比这更复杂,需要完成几个完全不同的步骤,每个步骤都需要以某种方式更改UI,您可以将任务划分为多个AsyncTasks,或者只是生成一个工作线程并使用Handler(在任务启动之前在UI线程中创建)使用您在UI线程中运行所需的任何代码来发布Runnables。

final Handler handler = new Handler();
new Thread() {
  public void run() {

    // do time-consuming step 1

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 1
      }
    });

    // do time-consuming step 2

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 2
      }
    });

    // do time-consuming step 3

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 3
      }
    });

  }
}.start();

实际上,无论AsyncTask是否符合您的需求,它都能达到您所需的控制水平。

答案 3 :(得分:0)

     Thread background = new Thread(new Runnable() {

                private final HttpClient Client = new DefaultHttpClient();
                private String URL = "http://blahblahxxx.com/media/webservice/getPage.php";

                // After call for background.start this run method call
                public void run() {
                    try {

                        String SetServerString = "";
                        HttpGet httpget = new HttpGet(URL);
                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        SetServerString = Client.execute(httpget, responseHandler);
                        threadMsg(SetServerString);

                    } catch (Throwable t) {
                        // just end the background thread
                        Log.i("Animation", "Thread  exception " + t);
                    }
                }

                private void threadMsg(String msg) {

                    if (!msg.equals(null) && !msg.equals("")) {
                        Message msgObj = handler.obtainMessage();
                        Bundle b = new Bundle();
                        b.putString("message", msg);
                        msgObj.setData(b);
                        handler.sendMessage(msgObj);
                    }
                }

                // Define the Handler that receives messages from the thread and update the progress
                private final Handler handler = new Handler() {

                    public void handleMessage(Message msg) {

                        String aResponse = msg.getData().getString("message");

                        if ((null != aResponse)) {

                            // ALERT MESSAGE
                            Toast.makeText(
                                    getBaseContext(),
                                    "Server Response: "+aResponse,
                                    Toast.LENGTH_SHORT).show();
                        }
                        else
                        {

                                // ALERT MESSAGE
                                Toast.makeText(
                                        getBaseContext(),
                                        "Not Got Response From Server.",
                                        Toast.LENGTH_SHORT).show();
                        }    

                    }
                };

            });
            // Start Thread
            background.start();  //After call start method thread called run Method