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

I'm an Android n00b so bare with me.

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?

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.


Need Your Help

SQL Server 2008: Can you have a query where you do a diff on a count from two tables and then output result

sql-server sql-server-2008

What I would like to do is produce a query which returns the difference between the sum of two other queries. I have tried, but I have failed. Here is what I tried:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.