Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from separate thread class to activity in Android

I'm trying to analyze audio using AudioRecord in a class. My problem is that I have no idea if the route I'm going to try and thread that into a separate process is correct. What I want to do is listen to that process in the main UI thread and keep updating a text box based on the data in the thread.

This is what I have so far:

//RecordActivity.java
[...]
public class RecordActivity extends Activity {
    final Handler mHandler = new Handler();
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };
    RecordThread t = new RecordThread();

private OnClickListener mClickListener = new OnClickListener() {

  public void onClick(View v) {
    t.start();

  }
}

//RecordThread.java
public class RecorderThread extends Thread {
[...]

@Override
public void run() {
[...audio process code...]
}

Is there a way to post back data from my RecordThread class to the RecordActivity class? Is there a way to connect the handler using 2 different .java files?

Also, is this even the correct way to go about this? Should I be using AsyncTask instead?

like image 936
wajiw Avatar asked Oct 14 '22 20:10

wajiw


1 Answers

Pass your mHandler as parameter to the constructor of you RecordThread class, and use mHandler.obtainMessage( ... ).sendToTarget() to pass data to the Activity class

On the RecordActivity class, declare and use the Handler as:

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    }

Then it dependes on how you called the obtainMessage(), if you used, for example, obtainMessage(int what, int arg1, int arg2) you can access these by using msg.what, msg.arg1, and msg.arg2.

like image 116
Filipe Miguel Avatar answered Oct 18 '22 03:10

Filipe Miguel