Android 中 handler.post 的 run 方法中未更新变量

问题描述 投票:0回答:1

我创建了一个新线程来处理我的 TCP 管理需求。我这样做是为了在 UI 线程执行各种套接字魔法时保持其活动状态。我遇到的问题是 ServerThread 中使用的变量 num 似乎没有在 handler.post() 的 run 方法中更新。它更改一次,但 while(true) 循环中的后续迭代不再更改其值。但是,在 handler.post() 之外,我注意到它正在正确更改。我已经包含了 logcat 的日志命令,以便查看 num 的值,这就是为什么我知道这就是发生的情况。问题是,我需要 run() 方法中的变量 num 来更新 UI 线程中的一些内容。

可能是我声明num的方式有问题。我没有在代码中包含我认为与我的问题无关的大部分内容,所以如果我错过了某些内容,请现在告诉我。这是我第一次涉足 android java 线程,因此非常感谢一些帮助。今晚精神力就耗尽了。

public class MainActivity extends Activity {
    private int num = 0;
    private Handler handler = new Handler();
    //Other declarations


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        //Do bunch of things including starting ServerThread
        //and creating a TCP server socket
        }

    public class ServerThread implements Runnable{
       public void run(){
       // ...
       // Do bunch of stuff including waiting for a client to connect
       try{                         
         BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
         while(true){ 
           num = in.read();
           Log.e("MainActivity", "A:" +num);       //<-- WORKS FINE
           if(num == -1) //client socket closed
             break;
           handler.post(new Runnable() {
              @Override
              public void run() {
                 Log.e("MainActivity", "B:" +num); //<-- DOES NOT WORK FINE
                 //Do bunch of stuff here with the variable num 
                 //including updating the UI thread
              }
           }
       }catch(Exception e){
              // ...
       }
    }
}
android multithreading handler runnable
1个回答
0
投票

我有类似的问题:当连接到服务器计时器时停止网络时,在整个连接到服务器的时间内没有连接时,没有正确删除时间,从第二次和其他时间开始,第一次就可以了!我的整个代码在这里:https://github.com/yavorkolev/vpn_android_client_hardcoded_server

© www.soinside.com 2019 - 2024. All rights reserved.