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 OnClickListen开发者_运维问答er() {
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?
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
.
I would recommend taking a look at the Android fundamentals. It gives you a good overview of the key application components within Android. I think this is a must read for anyone starting with Android.
A service might be what you need.
Keep in mind that services run on the main thread, so when executing expensive operations, you may want to checkout Handling Expensive Operations in the UI Thread.
精彩评论