简体   繁体   English

如何将数据从单独的线程类传递到Android中的活动

[英]How to pass data from separate thread class to activity in Android

I'm trying to analyze audio using AudioRecord in a class. 我正在尝试使用类中的AudioRecord分析音频。 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. 我想要做的是在主UI线程中监听该进程,并根据线程中的数据不断更新文本框。

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? 有没有办法将我的RecordThread类中的数据回发到RecordActivity类? Is there a way to connect the handler using 2 different .java files? 有没有办法使用2个不同的.java文件连接处理程序?

Also, is this even the correct way to go about this? 此外,这甚至是正确的方法吗? Should I be using AsyncTask instead? 我应该使用AsyncTask吗?

Pass your mHandler as parameter to the constructor of you RecordThread class, and use mHandler.obtainMessage( ... ).sendToTarget() to pass data to the Activity class mHandler作为参数传递给RecordThread类的构造函数,并使用mHandler.obtainMessage( ... ).sendToTarget()将数据传递给Activity类

On the RecordActivity class, declare and use the Handler as: RecordActivity类中,声明并使用Handler作为:

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 . 然后它依赖于你如何调用obtainMessage(),如果你使用了,例如,你可以通过使用msg.whatmsg.arg1msg.arg2来获取它们的obtainMessage(int what, int arg1, int arg2)

I would recommend taking a look at the Android fundamentals . 我建议看一下Android基础知识 It gives you a good overview of the key application components within Android. 它为您提供了Android中关键应用程序组件的良好概述。 I think this is a must read for anyone starting with Android. 我认为对于任何以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 . 请记住,服务在主线程上运行,因此在执行昂贵的操作时,您可能需要检查UI线程中的处理昂贵操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM