Java 在执行线程期间更新UI

Java 在执行线程期间更新UI,java,android,Java,Android,在我的应用程序中,我正在运行一个线程,其中执行了一些文本文件操作。在此期间,我还希望使用setText不断更新UI上的结果。请建议一条路 testThread = new Thread(){ public void run() { Log.i("TestApp","Test Thread Running"); runTest(); } }; 据我所知,在UI线程上执行

在我的应用程序中,我正在运行一个线程,其中执行了一些文本文件操作。在此期间,我还希望使用setText不断更新UI上的结果。请建议一条路

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

          }

        };

据我所知,在UI线程上执行耗时的操作以避免ANR是不好的。请建议一种可以同时完成这两项任务的方法。

与其使用use AsyncTask,不如使用use 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.
    }
}
试试这个:

  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();
}
private void runThread(){
新线程(){
公开募捐{
而(i++<1000){
试一试{
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
//在你的UI上做些什么
}
});
睡眠(300);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
}
}.start();
}

有几种方法。一种常见的模式是使用AsyncTask,但是如果您需要执行几个中间进度更新,AsyncTask最适合于每个步骤都相似的情况(例如下载文件并相应地为每下载一个xKB更新UI)。但在许多情况下,这是可以接受的

如果您的任务比这更复杂,包含几个完全不同的步骤,每个步骤都需要以某种方式更改UI,那么您可以将任务划分为几个异步任务,或者简单地生成一个工作线程并使用一个处理程序(在任务开始之前在UI线程中创建)使用需要在UI线程中运行的任何代码发布可运行性

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是否适合您的需要取决于您需要的控制级别。

Thread background=new Thread(new Runnable()){
     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
私有最终HttpClient客户端=新的DefaultHttpClient(); 专用字符串URL=”http://blahblahxxx.com/media/webservice/getPage.php"; //在后台调用之后。启动此运行方法调用 公开募捐{ 试一试{ 字符串SetServerString=“”; HttpGet HttpGet=新的HttpGet(URL); ResponseHandler ResponseHandler=新BasicResponseHandler(); SetServerString=Client.execute(httpget,responseHandler); threadMsg(SetServerString); }捕获(可丢弃的t){ //只需结束背景线程 Log.i(“动画”、“线程异常”+t); } } 私有void threadMsg(字符串msg){ 如果(!msg.equals(null)&&!msg.equals(“”){ Message msgObj=handler.obtainMessage(); Bundle b=新Bundle(); b、 putString(“消息”,msg); msgObj.setData(b); handler.sendMessage(msgObj); } } //定义从线程接收消息并更新进度的处理程序 私有最终处理程序=新处理程序(){ 公共无效handleMessage(消息消息消息){ 字符串aResponse=msg.getData().getString(“消息”); 如果((null!=aResponse)){ //警报消息 Toast.makeText( getBaseContext(), “服务器响应:”+AresResponse, 吐司。长度(短)。show(); } 其他的 { //警报消息 Toast.makeText( getBaseContext(), “未从服务器获得响应。”, 吐司。长度(短)。show(); } } }; }); //起始线程 background.start()//调用启动方法后,线程调用run方法
这将帮助您完成任务:@Jan Swing不适用于Android。谢谢。我需要更新整数值,以便类GetStuffAsyncyExtendesAsyncTaskInSteadValues不能正确显示,但我将对其进行排序。谢谢@NigamPatro@user3374737基本上,第一个是参数,您传递给
doInBackground()
,第二个是
onPublishPrgress()
,第三个是
onPostExecute()
,谢谢您的建议,但我更喜欢选择的答案。使用睡眠有点冒险,对吧谢谢你的建议谢谢你的建议。答:我选择的作品适合我的需要。谢谢
     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