[英]Call method from another object-java
I'm doing some Android development and I have an object, which doing a specific task. 我正在做一些Android开发,并且有一个对象在执行特定任务。 When that task is done I need to inform my main method (Main Activity), which is constantly running, that the process has been finished and pass some information about it.
完成该任务后,我需要通知不断运行的主方法(主活动)该过程已完成,并传递一些有关此方法的信息。
This may sound a bit unclear, so I'll give you an example: 这听起来可能还不清楚,所以我举一个例子:
Take a look at the setOnClickListener()
method in Android: 看一下Android中的
setOnClickListener()
方法:
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
//This method is called on click
@Override
public void onClick(View v) {
//The View is passed in an anonymous inner class
}
});
It waits for a button to be clicked and calls the onClick(View v)
method. 它等待一个按钮被单击,然后调用
onClick(View v)
方法。 I am seeking to achieve the same code structure. 我正在寻求实现相同的代码结构。
How to do this? 这个怎么做?
This is exactly Listener pattern that you use with views in android. 这正是您与android中的视图一起使用的侦听器模式 。 What you want to do is declare an interface in your class that's doing the job, and pass an instance of this interface.
您想要做的是在正在执行此工作的类中声明一个接口,然后传递该接口的实例。 Raw example:
原始示例:
TaskDoer.java : TaskDoer.java :
public class TaskDoer {
public interface OnTaskDoneListener {
void onDone(Data data);
}
public void doTask(OnTaskDoneListener listener) {
// do task...
listener.onDone(data);
}
}
Activity : 活动内容 :
public void doTaskAndGetResult() {
new TaskDoer().doTask(new TaskDoer.OnTaskDoneListener() {
public void onDone(Data data) {
// do something
}
}
}
You mentioned "process". 您提到了“过程”。 If you are truly doing something in a different process, then you need to look at interprocess communications (IPC).
如果您确实要在其他过程中做某事,那么您需要查看进程间通信 (IPC)。 Otherwise, you can use an interface:
否则,您可以使用一个接口:
Create a class called MyListener
: 创建一个名为
MyListener
的类:
public interface MyListener {
void onComplete();
}
In your class that will notify your activity: 在您的班级中,将通知您的活动:
MyListener myListener;
public void setMyListener(MyListener myListener){
this.myListener = myListener;
}
Then, when you are ready to notify your main activity, call this line: 然后,当您准备通知您的主要活动时,请致电以下行:
myListener.onComplete();
Last, in your MainActivity
implement MyListener
: 最后,在您的
MainActivity
实现MyListener
:
public class MyListener extends Activity implements MyListener {
///other stuff
@Override
public void onComplete(){
// here you are notified when onComplete it called
}
}
Hope this helps. 希望这可以帮助。 Cheers.
干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.