【问题标题】:Own Listener change UI-Thread in Android自己的监听器在 Android 中改变 UI-Thread
【发布时间】:2013-06-13 14:07:22
【问题描述】:


@first 对不起我的英语不好。
我创建了一个自己的监听器。我想更改 TextView,当从服务中调用 MainActivity 中的侦听器时。我自己的 Listener 的想法来自:

http://tseng-blog.nge-web.net/blog/2009/02/17/how-implement-your-own-listener-android-java/

在代码示例中,TriggerMethod() 是从服务中运行的计算线程调用的。 我解决了这个问题,但我发现它不是很好,因为在每个新活动中我都必须创建一个新线程。是否可以创建一个可以自动更改 UI 的接口/侦听器?
用于解决问题:
http://developer.android.com/guide/components/processes-and-threads.html

ResultListener.java:

public interface ResultListener {   
    public void onResultAvailable(double result);
}

SimuService.java:

public class SimuService extends Service {

    private ResultListener mResultListener = null;

    public void setResultListener(ResultListener listener){
        mResultListener=listener;
    }
  public void triggerMethode(){
        observeResultDouble=getObserveDouble;
        mResultListener.onResultAvailable(observeResultDouble);         
    }

主活动:

public class MainActivity extends FragmentActivity{
    TextView txtView;
    ResultListener mResultListener;
    SimuService mSimuService;

    protected void onCreate(Bundle savedInstanceState) {
        txtView = (TextView) findViewById(R.id.txtServiceTime);
        //Create Service .....an Bind
        mResultListener = new ResultListener() {            
            @Override
            public void onResultAvailable(double result) {
                txtView.setText("Result: "+result);
            }
        };
        mSimuService.setResultListener(mResultListener);

    }

我的解决方案:

ResultListener = new ResultListener() {         
            @Override
            public void onResultAvailable(double result) {
                this.result=result;
                runOnUiThread(setNewDataToUI);  
            }
        };

private Thread setNewDataToUI = new Thread(new Runnable() {

    @Override
    public void run() {
        txtView.setText("Result: "+result);

    }
});

【问题讨论】:

    标签: java android


    【解决方案1】:

    首先:如果你在一个 Activity 中引用一个 Service,这个 Service 就变得毫无用处了。服务的优点是,它们是松散耦合的,可以独立于活动(=用户看到的内容)及其生命周期中工作,甚至可能在它们自己的过程中。因此活动-服务通信是通过意图或进程间语言AIDL,而不是通过回调。如果您想异步执行某些操作,请使用 AsyncTask。

    对于您的主要问题:正如您所发现的,您只能在 UI 线程上修改 UI。因此,按照设计,将更改 UI 留在组件中,这是对此负责的(活动或片段),这将防止需要 runOnUiThread()

    您的代码似乎 txtView.setText("Result: "+result); 将在 Activity 中执行,但它不会。它将在服务中执行,该服务(正如我之前所暗示的)不在 UI 线程上运行。问题是,我不明白你到底想达到什么目的,所以很难给你一个替代解决方案。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2019-12-14
    • 2012-04-10
    • 2021-08-22
    相关资源
    最近更新 更多