Java – Android – end activity within rendering thread
Good afternoon.
I am not familiar with the activity life cycle in Android and read it as much as possible, but I can't think of a good way to solve the following problems
I have an activity with GL surfaceview, which can draw all kinds of content on the screen In this GL surfaceview rendering thread, I perform all rendering and actual update logic (I will eventually separate it)
My trouble comes from a "screen" drawn in the renderer. I want to end the activity and let it call various lifecycle methods
Usually I can use system Exit (0) perform this operation; However, ending the activity in this way does not seem to call onstop(); Ondestroy(); method.
It may just be that I was stupid and didn't see a simple way to do this, but there is no way to access the activity and call the activity finish(); No need to pass reference documents all the time?
This may not be an Android problem, but more like a general Java problem? Sorry, I'm both a little rusty Maybe if someone can explain roughly how they deal with such problems in their application
Solution
Instead of calling activity directly from the rendering thread, you need to follow thread safety rules finish(). The best way to deal with this problem is to publish runnable back to the event queue of the UI thread Let runnable call activity finish().
You do not have to pass the activity to the area where you plan to stop the activity That's what I'm going to do Pass the activity to the class you instantiated in oncreate() It's like:
public void onCreate( ... ) { MyRenderer renderer = new MyRenderer( glSurface,this ); }
Then I did something similar in myrenderer:
public void someMethodInRenderer() { if( stop ) { stop(); } } public void stop() { Handler handler = new Handler(); handler.post( new Runnable() { public void run() { activity.finish(); } } ); }
Note that the handler is used to post back to the UI thread This makes it safe to call activity finish(). I can't find any specific information in the documentation that it's safe or unsafe to call finish () from another thread, so I publish it in terms of security
Things to remember If somemethodinrender () goes deep inside the program, you don't have to access the activity instance directly You only need a reference and eventually call the activity to complete it So there may be a reference to another part of the system that you pass to the method that you can add stop () So stop () and somemethodinrenderer () can be in the same class or in different classes This is the choice you have to make Ultimately, this is an architectural issue that you have to decide