【问题标题】:Is it possible to call a Interface function from thread?是否可以从线程调用接口函数?
【发布时间】:2019-08-01 13:41:38
【问题描述】:

可能我的问题不是很好,但我真的不知道如何正确地问。

我想做什么:

public interface cooleInterface {
    void soCoolFunction(String a);
    }

我的第一个问题是,如何定义方法? 我想在 Activity 中定义方法,例如:

public void soCoolFunction(String a){
Log.d(TAG, "You Logged " + a);
}

现在我想从像这样的线程调用它

public class WhatEver extends Thread implements cooleInterface{

public void run(){
@override
soCoolFunction("Hello");

这甚至可能吗?或者如何在不使用静态的情况下调用其他没有实例的类中的方法?

【问题讨论】:

  • 你可以在WhatEver类中传递cooleInterface的实例。

标签: java android interface


【解决方案1】:

当然,这是可能的。但是,考虑到线程完成时侦听器可能为空,抛出 NPE...
更新:代码 线程,

public class MyRunnable implements Runnable {

    MyInterface interface;

    public MyRunnable(MyInterface interface) {
        this.interface = interface;
    }

    public void run() {
        interface.onRunnableDone("Hello")
    }
}

界面,

public interface MyInterface{
    void onRunnableDone (String runnableString);
}

终于开始活动了,

   public class MyActivity extends Activity implements MyInterface {

    Runnable r = new MyRunnable(this);
    new Thread(r).start();

    @Override
    onRunnableDone(String runnableString){
        //do something with the string
    }
}

【讨论】:

    【解决方案2】:
    public class WhatEver extends Thread {
    
       private final CooleInterface listener;
    
       public WhatEver(CooleInterface listener) {
          super();
          this.listener = listener;
       }
    
       public void run() {
          super.run();
          this.listener.coolFunction("Hello");
       }
    }
    

    【讨论】:

    • 你能用 Java 写这个吗?
    • 给我1分钟^^
    • 作为监听器我需要传递什么?什么是“你的听众”?自定义监听器?!
    • 这是你的界面
    • 引用@HydroHeiperGen This is working but useless。如果有 100 种方法可以获得相同的结果,最好删除问题或提供结果(如果有的话)。
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2015-05-22
    • 2012-09-24
    相关资源
    最近更新 更多