简体   繁体   English

如何在线程中返回上一个活动

[英]How to return to previous activity when in a thread

Basically from the MainActivity, I start a new activity called GameManagerAct.基本上从 MainActivity,我开始了一个名为 GameManagerAct 的新活动。 In GameManagerAct, I set my content view as a GameManager, which is just a class that contains a thread.在 GameManagerAct 中,我将我的内容视图设置为 GameManager,它只是一个包含线程的类。 As it has a thread, it is stuck in my GameManager object.因为它有一个线程,所以它卡在我的 GameManager 对象中。 When I reach a point in the GameManager object where I want to return to the previous activity (MainActivity), how would I do this?当我到达 GameManager 对象中的某个点时,我想返回到前一个活动 (MainActivity),我该怎么做? Since it is just a class and not an Activity, it doesn't have access to the finish() command for GameManagerAct.由于它只是一个类而不是活动,因此它无权访问 GameManagerAct 的 finish() 命令。

I've tried moving the code from the GameManager object into the GameManagerAct, but this doesn't work.我已经尝试将代码从 GameManager 对象移动到 GameManagerAct 中,但这不起作用。

// In MainActivity.java // 在 MainActivity.java 中

startActivity(new Intent(MainActivity.this, GameManagerAct.class));

// In GameManagerAct.java // 在 GameManagerAct.java 中

GameManager gm = new GameManager(this);
setContentView(gm);

// In GameManager.java // 在 GameManager.java 中

else if (quitRect.contains(movePointX, movePointY)) {
    // ends GameManagerAct activity and returns back the MainActivity
}

I want the setContentView to return back to the one for MainActivity.我希望 setContentView 返回到 MainActivity 的那个。 Currently, nothing happens cause I don't know how to do it.目前,没有任何反应,因为我不知道该怎么做。

you should make interface to access your view (activity) from your GameManager class, and when your work finish it call the method of your interface, in that interface method you can finish the activity.您应该创建接口以从您的 GameManager 类访问您的视图(活动),当您的工作完成时,它会调用您的接口方法,在该接口方法中您可以完成活动。 or you can use observable design pattern too.或者你也可以使用可观察的设计模式。

interface GameInterface{
 void workDone();
}

in your activity implement this在你的活动中实现这个

GameManagerAct implement GameInterface{

and overrite it like:并覆盖它,如:

void workDone(){
this.finish();
}

pass it to GameManager classs.将它传递给 GameManager 类。 and in it use the method when work done.并在工作完成时使用该方法。

interfaceObject.workDone();

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

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