Determining onCreate() VS onRestartingFromBackGround() in Android app - java

I'm having a small problem with the Android app I'm designing.
I need to run some code whenever either of these 2 events happen:
1. The app is NOT running in the background, so the user launches it.
2. The app IS already running in the background, so the user is really
just re-opening it.
(I only need to run the code once, not twice.)
No matter where I put the call to my code (onCreate, onStart, onRestart, onResume, etc) I always have undesired affects:
A. My code gets run twice when #2 happens.
B. My code runs even when the user is just moving from
MAIN to a SUB-ACTIVITY, then back to MAIN again.
C. My code doesn't run at all.
Isn't there come kind of distinction I can make to determine: onCreate() and onRestartingFromBackGround()?
I thought I could use onRestart(), but I was VERY surprised to see that onRestart() runs even just when I do #B. (Is #B really considered a "restart" of my app????)

From a pure java standpoint, you could use a loading thread for when the icon is first pressed. This loading thread can poll the phone to see if the main activity thread is currently running or not, then from your loading thread, move to the correct piece of code. For ANDROID, I THINK, that you will poll the process name, or process ID...anyone ever poll the OS for processes??

Related

Weird bug - the application is stuck, but the UI still responds

So.. I have a really strange bug in my application.
At some point, for some reason, application stops handling some events, for example: adapters wont update after notifydatasetchanged call, mapview is not responding at all, activities wont start, any kind of fragments transaction does nothing - list goes on.
But at the same time, if I'll press some button - it displays ripple effect and fires onClick (and even network request started by this click finishes successfully), this means that main thread still works correctly.
I am able to hide and show views programmatically, receive firebase realtime db events and do all kind of business logic.
My wild guess is that either some thread responsible for this kind of stuff stuck (deadlock?), or maybe this is how application works after OutOfMemoryException? Because this usually happens after working with map a lot (Yandex Map).
I really don't understand whats going on.
I figured it out. This weird behaviour was due to a lot work with UI elements from one background thread. I don't know why and how project was still working, but thats the case. Something breaks after N calls to UI from non-UI threads.
Also, on Android 8 it breaks right away, but on lower api levels application can work for hours before breaking.

Keep thread running after onDestroy

I am currently building an android application that will be used as an anti theft sort of application. Basically, once the alarm has bee launched, the application will monitor the accelerometer to detect movement. If it does, the user will have 15 seconds to enter a set password to deactivate the alarm, otherwise : BIIIIIP!
My problem is the following: how do I manage to keep the monitoring and counter process running after the activity is destroyed (if for example the user presses back) in a way that I can access it again from a notification.
I was thinking of using a thread to run the monitoring and counting process and when the notification was pressed, for example, the class could, in it's onCreate method, be aware whether an already existing thread is running and if so, get the handle to it?
Thanks.
What you are looking for is a Service. They are meant for this exact purpose; to run on the background (this does not mean a background Thread ) even if there are no Activities running.
You should consider using services for this purpose. Here is one of the example: http://blog.kozaxinan.com/2012/08/using-accelerometer-when-screen-off_16.html

TouchScreen Nokia C5 -J2ME's Command Action buttons and Scrolling do not work after changing system time

I am starting my app, and it is working well... but After...:
Going to "Settings-> Phone-> Date and time",change the time backward.(MyApp is onbackground)
Re-opening tested application
Trying to use left command action and rıght command actıon.... scrolling...
J2ME's Actıon Commands aren't working at all. Also touchscreen's scrolling is not working...!
... start executing the application is operating normally. So "im2amit" who is from forum.nokia, proposed to re-create my object. I use HideNotify()/showNotify() for sense app is background.. they work good, But if I change system time backward, showNotify Method doesn't work..?
Does it work if you end the application after changing time and again start it ?
If yes, its the problem with the application going in background. I mean whenever your application goes in background, it actually looses some active objects from memory.
So instead of changing time, try to do something else while your application is in background, I guess it will also yield the same results.

Where to start debugging, when you get the "Activity is not responding, Force Close, Wait"?

I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.
The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:
Sorry:
Activity xxxxx is not respoding.
Force Close - Wait
If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.
I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.
any ideas?
since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.
//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
bitmap = graphic.getGraphic();
coords = graphic.getCoordinates();
canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
bitmap = _currentGraphic.getGraphic();
coords = _currentGraphic.getCoordinates();
canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
Android has a relatively good profiler support built in.
When you know the place where this ADNR will show up (e.g. with in one method of your activity, you can put that block in a tracing block:
Debug.startMethodTracing("xyz");
<your code goes here>
Debug.stopMethodTracing()
This will upon activation write a trace file to /sdcard/xyz.trace
You can later (after such a ADNR occurred) obtain it via
adb pull /sdcard/xyz.trace
and analyze it via
traceview xyz.trace
Within the traceview screen, you see the method with its called methods and you can then see the timings.
See http://developer.android.com/guide/developing/tools/adb.html and http://developer.android.com/guide/developing/tools/traceview.html
Are you doing network connections on the main thread? Or Time.sleep()'s. Or extremely long running calculations?
Something in your app's main thread is taking more than 5 (or is it 10?) seconds to complete.
I think you are creating the 30 second sleep on the main thread, if so, the application will be unresponsive for about 30 seconds and the android system will show force close dialog will show up after 5 second. Try creating the 30 second pause and action on a new thread. Check android developers site for more information about threads.
And if you don't know where to start debugging, check your logcat log and search for errors or warnings. Check this -> http://www.droidnova.com/debugging-in-android-using-eclipse,541.html for some information about logcat.
Hope that helped. :) Good luck.
Edit: Then i think that you should put the functions that the wait button performs inside a new thread, so that the application becomes responsive instantly and the child thread remains unresponsive, which doesnt matter.
Edit Again: oh, i get it now, sorry for the misunderstanding, so you are not sure where the problem is, try searching for any network connections, sleep/pauses in your code. Oh, and connect your phone to your computer, run the app by pressing F5 and try to search for warnings or errors in logcat just when the force close box opens. And try to copy the logcat log and send it to me, and ill check whats wrong.
You can use the new StrictMode to detect what is causing your UI thread to hang.
Take a look at this link.
It is only available for GingerBread (API level 9), so you can just test it on the emulator, perform the necessary cleanup, and then remove the StrictMode code

Is there a function in Android analogous to "int main" in C/C++ which contains the program's main loop?

Normally in a C or C++ program there's a main loop/function, usually int main (). Is there a similar function that I can use in android Java development?
As far as an Android program is concerned there is no main().
There is a UI loop that the OS runs that makes calls to methods you define or override in your program. These methods are likely called from/defined in onCreate(), onStart(), onResume(), onReStart(), onPause(), onStop(), or onDestroy(). All these methods may be overriden in your program.
The fundamental issue is that the OS is designed to run in a resource constrained environment. Your program needs to be prepared to be halted and even completely stopped whenever the OS needs more memory (this is a multitasking OS). In order to handle that your program needs to have some of all of the functions listed above.
The Activity lifecycle describes this best (your program is one or more Activities, think of an Activity as a screen).
Bottom line: Your program 'starts' at onCreate() through onResume() but the OS is running the loop. Your program provides callbacks to the OS to handle whatever the OS sends to it. If you put a long loop at any point in your program it will appear to freeze because the OS (specifically the UI thread) is unable to get a slice of time. Use a thread for long loops.
In Android environment, there is no main(). The OS relies on the manifest file to find out the entry point, an activity in most case, into your application.
You should read http://developer.android.com/guide/topics/fundamentals.html for more detail.
According to:
http://developer.android.com/guide/tutorials/hello-world.html
The application class must support a method for each activity that the Application
supports. In the general case, the onCreate is probably equivalent to the main/top
function for your needs.
Maybe it's possible by creating a timer and execute custom functions at every tick, reset the timer when it's at a specific time
The above answers provide a "why" as to there's no "main loop" on Android (which is important to understand). I'll offer a solution to the implied question, instead, as many visitors here will be looking for exactly that.
I believe the appropriate thing to do, here, would be to create an AsyncTask which operates as your "main loop". Or better yet, design your main loop to run as a java.util.concurrent future, which can be started and ended during lifecycle events (like rotation!), using signaling (keep your data separate). The AsyncTask API is deprecated, because it was complex, and handling it properly amounted to writing code that would, effectively, operate as an AsyncTask which cleaned up when the next problematic lifecycle event transpired.
Keep in mind that this will be a separate thread from the UI, and, as such, will be required to respond in short order to UI thread events, like "onPause" and "onDestroy". If your app does not respond within a certain period of time (~5 secs, iirc) to these events, or user input events, it will be killed by the OS. It's really prudent, for a real-time app, to be able to fully respond to these events in under 1 sec, even on the lowest-end device. You can use synchronization primitives to notify other threads that their response is pending, and they can use them to signal when they are finished (or simply end, in the case of a future).

Categories