Pass a Message From Thread to Update UI

前端 未结 2 530
粉色の甜心
粉色の甜心 2021-02-10 14:25

Ive created a new thread for a file browser. The thread reads the contents of a directory. What I want to do is update the UI thread to draw a graphical representation of the fi

相关标签:
2条回答
  • 2021-02-10 14:56

    It seems passing simple messages is int based... What I needed to do was pass a Bundle

    using Message.setData(Bundle) and Message.getData(Bundle)
    

    So Happy =0)

    //Function From Within The Thread
    
    public void newProjectCreation() {
    
    Message msg =  new Message();
    Bundle bundle = new Bundle();
    
    bundle.putString("Test", "test value");
    msg.setData(bundle);
    
    handler2.sendMessage(msg);
    }
    
    //Handler in The UI Thread Retreieves The Data
    //And Can Update the GUI as Required
    
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
    
        Bundle bundle = msg.getData();
        Toast.makeText(New_Project.this,bundle.getString("Test"),Toast.LENGTH_SHORT).show();
    
    }
    
    };
    
    0 讨论(0)
  • 2021-02-10 15:04

    Check out AsyncTask for this kind of stuff. It's really much more elegant than rolling your own handler and passing messages back and forth.

    http://developer.android.com/reference/android/os/AsyncTask.html

    0 讨论(0)
提交回复
热议问题