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.
Related
I have a GUI and the GUI is starting another thread (Java). This thread is starting a class which is crawling many websites. Now I want to show in the GUI how many websites are crawled and how many are left.
I wonder what's the best solution for that.
First idea was to start a timer in the GUI and periodically ask the crawler how many is left. But I guess this is quite dirty...
Then one could pass the GUI to the crawler and it is calling a GUI method every time the count of ready websites changes. But I don't think that's much better?
What is the best way to do something like that?
It depends.
Ask the crawler how much work it is done isn't a bad idea. The benefit is you can actually control when an update occurs and can balance out the load.
The downside is that the information may go stale very quickly and you may never get accurate results, as by the time you've read the values, the crawler may have already changed them.
You could have the crawler provide a call back interface, which the GUI registers to and when the crawler updates it's states, calls back to the GUI.
The problem here is the UI may become swamped with results, causing to lag as it tries to keep up. Equally, while the crawler is firing these notifications, it isn't doing it's work...
(Assuming Swing)
In either case, you need to make sure that any ideas you make to the UI are made from within the Event Dispatching Thread. This means if you use the callback method, the updates coming back will come from the crawlers thread context. You will need to resync these with the EDT.
In this case you could simply use a SwingWorker which provides mechanisms for syncing updates back to the EDT for you.
Check out Concurrency in Swing for more details
register a callback function to your thread. when your data is dirty, invoke this callback function to notify GUI thread to update. don't forget to use synchronization.
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??
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
I can't seem to find any documentation on the details of an Activity's run loop for Android.
Apple documents the "anatomy of a run loop", and that's pretty much what I'm looking for. The Android documentation just says "Activity Is Running" in its life cycle state diagram. Obviously that's backed up by some sort of run loop.
Anyone have some insight (aka Documentation) into the internals of an Activity's run loop?
edit - I should clarify that I presume the run loop is actually owned and run by the main UI thread. The current Activity's functionality is likely injected into this runloop at a certain point. I'm interested in the overall UI thread run loop, as well as what role the Activity takes in it.
The short answer is, "don't worry about it, it's done for you."
Activities and other constructs sit on top of android.os.Looper, communicating with it through instances of android.os.Handler. A Looper manages your "run loop," dispatching messages from a queue and blocking the thread when it's empty. Handlers communicate with a thread's Looper and provide a mechanism for working with the message queue.
Most of the time you won't need to work with either one directly. Lifecycle events for your major application components like Activities and Services will be dispatched to your code. If you're curious as to what's under the hood, sources for both are available:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Looper.java
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Handler.java
Updated:
There's really nothing specific being referred to by "Activity is running." The Activity is simply displaying its UI, handling input, executing any necessary functions, and starting another Activity.
If you're interested in what implications multi-threading would have on the run-loop, there isn't really a concrete relationship. Your threads can just do their work, and the Activity's state will function independently and automatically update its UI (provided you call postInvalidate() correctly).
Original:
Take a look at the first diagram on this page: http://developer.android.com/reference/android/app/Activity.html
It specifies the "lifetime" of each Activity and what states it can be in, if that's what you're looking for.
I'm developing an android app (if you want more info http://www.txty.mobi) and I am having some problems with dialogs management. I'm quite new to Android so the way I'm doing things completely wrong. If the case please just say so pointing me to the right documentation to follow.
Background:
The main blocks of the app so far are one activity and one Service (which derives from IntentService).
The actvity needs to interact with the service in just two occasions: start/stop the service. The intent service will self regulate its lifetime using the AlarmManager.
A typical flow when clicking on start/stop:
1) the activity on its onResume registers a broadcast receiver to events sent by the service (unregisters it in the onPause)
2) the activity starts a indeterminate progress dialog
3) the activty sends a single shot alarm event (either start or stop) which will be send **straight away to the service
4) the service does what it needs to do to start
5) the service emits a broadcast event basically saying "done"
6) the activity receive this event and gets rid of the dialog.
The Problem:
The activity can lose its foreground status let's say if the user switches focus or a call is received, so the onPause method is called (at this point the activity could even be killed by the system to claim memory). obviously if this is the case the activity will never receive its broadcast event because the receiver has been unregistered. This will leave the app in the awkward situation, when the activity is brought again to the front, of having a dialog that you can't kill nor will never get rid of.
The (possible??) solution:
The way I am handling this now (apart for keeping the broadcast receiver in place) is by creating a utility class that uses preferences to keep track of which operations are being executed and their status:
Activity
- in the onResume using my utility class gets the list of operations the activity is waiting for
- check their status
- if they are completed perform some actions accordingly (in my case get rid of dialog!)
- delete the operation from the preferences.
- just before asking for a operation to the service it saves it to the preference using my utility class.
Service
perform operation and save state of the operation to the preference using my utility class.
emit broadcast.
Disasters happen!
Now this saves me in a normal situation, but if a disaster happens (i.e. with the task killer app you kill everything) the service might be killed before it can save the status of the operation I am stuck as before (the activity will think the operation is still going on so it won't touch the dialog). So as for now I add a Dismiss button to very dialog just in case :)
Now all of this looks too complicated for what I think should be a fairly common thing to do. That's why, as said at the beginning of the post, I might (very likely!) be completely wrong.
Any ideas? Apologies if this question has been asked already, I looked around but didn't find anything. Please point me to any resource online explaining this.
Thanks and sorry for the lenghty post :P
Luca
Have you tried using a StickyBroadcast? This caches the latest broadcast, so it can be received onResume. Please see this post.