Sending a message from a thread to update an interface

Ive created a new thread for the file browser. The stream reads the contents of the directory. I want to update the user interface stream to draw a graphical representation of files and folders. I know that I cannot update the user interface from a new thread, so I want:

while the file scan stream iterates through directories, files and folders pass the file path string back to the user interface stream. The handler in the user interface thread then draws a graphical representation of the file passed back.

public class New_Project extends Activity implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.d("New Thread","Proccess Complete."); Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); } }; public void fileScanner(){ //if (!XMLEFunctions.canReadExternal(this)) return; pd = ProgressDialog.show(this, "Reading Directory.", "Please Wait...", true, false); Log.d("New Thread","Called"); Thread thread = new Thread(this); thread.start(); } public void run() { Log.d("New Thread","Reading Files"); getFiles(); handler.sendEmptyMessage(0); } public void getFiles() { for (int i=0;i<=allFiles.length-1;i++){ //I WANT TO PASS THE FILE PATH BACK TU A HANDLER IN THE UI //SO IT CAN BE DRAWN. **passFilePathBackToBeDrawn(allFiles[i].toString());** } } } 
+4
source share
2 answers

Check out AsyncTask for this kind of thing. It really is a lot more elegant than wrapping your own handler and sending messages back and forth.

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

+3
source

It seems that passing simple messages is int based ... What I needed to do was pass the 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(); } }; 
+16
source

Source: https://habr.com/ru/post/1335721/


All Articles