0

I would like to know if there is a way to identify that my App entered background from the ndk.

I have an application that spawns a pthread with

pthread_create(&_thread, NULL, methodToCall, NULL); //create a thread 

Now this is all working perfectly fine. My problem is I only need the thread to run while the app is active. On iOS this is not a problem since the created thread is suspended by the system. On android however it continues to run even on the lock screen until you completely stop the app.

This is of course not so good for battery life. I know I could use a JNI Call from my Activities onStop() method. But this seems rather complicated.

So is there a better way for detecting within jni / c++ that my app has become inactive?

Arne Fischer
  • 922
  • 6
  • 27

1 Answers1

0

I think you cannot access your android app state from your c++ thread without using some message passing function. Since your app suspends (when the user closes the app or screen) you cannot pass messages from android to your c++ thread.

I can think of two possible solutions that might work for you: 1. When your activity "suspends" - the "OnPause()" method will be called, and there you can "stop" your thread or make it sleep. Then in the "OnResume()" method you can start it again or wake it up, depends on what thread does (how you use it).

2.You can have a flag that checks whether the app has suspended or not. Then make your c++ thread sleep for a few seconds/milisecs and check that flag - if the flag is on - stop your thread, otherwise continue. In this case you can't wake up your thread, unless you perform an action similar to the first (make it sleep/wakeup whenever the app suspends/reactivates).

Hope this helps, Tom.

Tom
  • 1,105
  • 8
  • 17
  • Yes. the big question is not how to suspend a thread when going background/offscreen, but how to reactivate it when the app returns to foreground. – Alex Cohn Jun 26 '14 at 11:11
  • Alright, as I have said you need a "flag" to tell you whether you should suspend the thread or not, and change the flag when you want to wake the POSIX (C++) thread. Here is a pretty good example how to accomplish this: http://stackoverflow.com/questions/14924469/does-pthread-cond-waitcond-t-mutex-unlock-and-then-lock-the-mutex – Tom Jun 26 '14 at 12:25