如何在Android中实现回调? [英] How to realize a callback in android?
问题描述
也许我对这个主题的了解很小,以至于"callback"一词不正确,对此感到抱歉.
Maybe my knowledge about this topic is so small, that the word "callback" is not right here, sorry about that.
如果我在任何类/活动/其他线程中启动一个线程,并在完成后希望它从启动该线程的实例(类/活动/其他线程)中执行其他代码,那么我如何实现呢?
If I start an thread in any class/activity/other thread and after finishing I want it to execute some other code from the instance (class/activity/other thread) which started the thread, how do I realize that?
目前,我是这样的:
这里是伪代码.
// Method inside class/activity/other thread
private void startThread(){
MyThread thread = new MyThread(this);
thread.start();
}
在线程内
public class MyThread extends Thread{
private (class/activity/other thread) instanceAbove;
public MyThread ( (class/activity/other thread) instanceAbove){
this.instanceAbove = instanceAbove;
}
public void run(){
//Do some stuff
finish();
}
public void finish(){
instanceAbove.MyThreadFinishMethod();
}
}
我认为这不是一个好方法,但是您能举个例子吗?
I think this is not a good way, but can you give me an example?
使用接口可用于AlertDialog
,因为我可以使用onAppend()
.但是,在这种情况下,我不知道如何使用它们.
Using interfaces is working for AlertDialog
s, because I can use onAppend()
. However, in this case, I don't know how I could use them.
推荐答案
您可以轻松地使用interface
并相应地从调用活动/类/其他线程中处理回调.这是一个例子.
You can easily use an interface
and handle the callback accordingly from your calling activity/class/other thread. Here is an example.
首先定义一个类似于以下内容的接口.
Define an interface like the following first.
public interface ThreadFinishListener {
void onFinish();
}
让我们假设您正在从Activity
实例化Thread
.因此,像下面这样在您的Activity
中实现侦听器.
Let us assume you are instantiating a Thread
from an Activity
. Hence implement the listener in your Activity
like the following.
public class MainActivity extends AppCompatActivity implements ThreadFinishListener {
// .... Other functions in your activity
@Override
void onFinish() {
// Do something when the Thread is finished and returned back to the activity
// This is actually your callback function.
}
}
现在修改Thread
类的构造函数,以便可以将侦听器传递给它.
Now modify the constructor of your Thread
class so that you can pass the listener to it.
public class MyThread extends Thread {
private ThreadFinishListener listener;
public MyThread(ThreadFinishListener listener){
this.listener = listener;
}
public void run(){
//Do some stuff
finish();
}
public void finish() {
// This will invoke the function call in your activity
listener.onFinish();
}
}
现在,在初始化Thread
时,您可能希望按以下方式将侦听器传递给它.
Now while initializing your Thread
, you might want to pass the listener to it as follows.
MyThread thread = new MyThread(this);
thread.run();
我希望足够.
这篇关于如何在Android中实现回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!