Creating global Runnable? - android

So, I've implement sync mechanism, that uses Runnable.
The thing with Runnable is, that you have to make sure it's properly created and destroyed in Activity. What happens if you have alot of activities? - Alot of boilerplate code.
Is there a way to create a single instance Runnable for whole application?
Is it okay to initialize it in SomeClass extends Application as its app entry point? If so, how would one solve cases as such: SomeClass.onCreate() will hit even if user receives notification (that would also mean, that sync happens every time user gets a notification - which is terrible).

Why don't you using life cycle aware app component like - LiveData and ViewModel from android app architecture components. This is the best solution with AsyncTask.
With Runnable you don't have any control to stop or resume your execution with activity lifecycle. Because if a Runnable doing task in background it will complete any how and it causes defenitly memory leak.
Another easy solution is you can try using RxJava and RxAndroid, so simple in less code, see this.
And if you still want traditional way you can try this.

Related

issue with android.os.Messenger and android.os.Handler with rotation change

Im trying to use the pattern of Activity-Service-Messenger to comunicate my Activity and Service. (like explained here http://viktorbresan.blogspot.mx/2012/09/intentservice-and-inter-process.html) Basically it says that i should create a Handler inside my Activity, and then create a Messenger and send that via putExtra() to my Service. The Service would then post messages to the activity ussing the Messenger.
My problem is that if i rotate the emulator, the Handler associated with the Messenger holds a reference to a destroyed activity. This causes not to refresh the interface of the new activity. I tried to put Messenger in onSaveInstanceState(). Eventought i can save the Messenger, the Handler is still referencing my past activity and i cant find a way to retrieve my Handler from the Messenger to set the new activity.
Edit:
Im avoiding to using:
android:configChanges="orientation|keyboardHidden"
onRetainNonConfigurationInstance()
Edit:
I used HalR idea of using a singleton and keep the handler there. It works really good, althought i can see that this pattern implies a careful cleaning of the references on the singleton.
Finally im also testing on the idea of using Activity-Service that was commented by Hoan Nguyen
I'm not sure that its appropriate for this case, but there are many people who have been frustrated by losing their activity when it rotates, or having to set complex stuff up every time they get a new activity.
Some people will create singletons that they use for referencing, then keep the Handler in there.
Others will extend the application class and put stuff in there. If you have a lot of complex things you are wanting to set up once, those are techniques you can use.
Keeping your app fluid and your making your activities independent of one another is a better overall philosophy, so its best to avoid anything global, but sometimes you gotta do what you gotta do.
Rotating the device at least pauses and resumes your activity according to the lifecycle. I think you are aware of the consequences.
Maybe stopping and starting a new service is the only right solution here. i worked as well with global states, but it will just always be easier when, you make every activity independent like a "single application".
edit: ok it's a messenger service... so stopping and starting is not a solution. so maybe you can register and unregister your messengers.

AsyncTask for longer than a few seconds? [duplicate]

This question already has answers here:
Android AsyncTask for long running operations
(4 answers)
Closed 9 years ago.
The API reference states,
AsyncTasks should ideally be used for short operations (a few seconds
at the most.)
Is the problem with a doInBackground that takes, say, 30 seconds that the thread pool might run out of threads? And if that's the reason, would it cease to be a problem if I ensure my app will never have more than one such long running doInBackground executing concurrently?
The answer given by #Walter Mundt is correct. Nevertheless, I would like to add a complement of information and give a pointer to a library that can be used for long running AsyncTask.
AsyncTasks have been designed for doing stuff in background. And, yes, it's right that if your AsyncTask lasts for two long, then you will face 2 different issues :
Activities are poorly tied to the activity life cycle and you won't get the result of your AsyncTask if your activity dies. Indeed, yes, you can but it will be the rough way.
AsyncTask are not very well documented. A naive, though intuitive, implementation and use of an asynctask can quickly lead to memory leaks.
RoboSpice, the library I would like to introduce, as proposed by #Walter Mundt, uses a background service to execute this kind of requests. It has been designed for network requests (potentially long running by nature), but it could be easily adapted to execute just long running tasks, unrelated to network. I would be glad to add a patch to it.
Here is the reason why AsyncTasks are bad for long running tasks. The following reasonning is an adaptation from exerpts of RoboSpice motivations : the app that explains why using RoboSpice is filling a need on the Android platform.
The AsyncTask and Activity life cycle
AsyncTasks don't follow Activity instances' life cycle. If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes.
And when it completes, the AsyncTask won't update the UI of the new Activity. Indeed it updates the former instance of the activity that
is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you
use, for instance, findViewById to retrieve a view inside the Activity.
Memory leak issue
It is very convenient to create AsyncTasks as inner classes of your Activities. As the AsyncTask will need to manipulate the views
of the Activity when the task is complete or in progress, using an inner class of the Activity seems convenient : inner classes can
access directly any field of the outer class.
Nevertheless, it means the inner class will hold an invisible reference on its outer class instance : the Activity.
On the long run, this produces a memory leak : if the AsyncTask lasts for long, it keeps the activity "alive"
whereas Android would like to get rid of it as it can no longer be displayed. The activity can't be garbage collected and that's a central
mechanism for Android to preserve resources on the device.
Progress of your task will be lost
You can use some workarounds to create a long running asynctask and manage its life cycle accordingly to the life cycle of the activity. You can either cancel the AsyncTask in the onStop method of your activity or you can let your async task finish, and not loose its progress and relink it to the next instance of your activity.
This is possible and we show how in RobopSpice motivations, but it becomes complicated and the code is not really generic. Moreover, you will still loose the progress of your task if the user leaves the activity and comes back. This same issue appears with Loaders, although it would be a simpler equivalent to the AsyncTask with relinking workaround mentionned above.
Using an Android service
The best option is to use a service to execute your long running background tasks. And that is exactly the solution proposed by RoboSpice. Again, it is designed for networking but could be extended to non-network related stuff. This library has a large number of features.
You can even get an idea of it in less than 30 seconds thanks to an infographics.
It is really a very very bad idea to use AsyncTasks for long running operations. Nevertheless, they are fine for short living ones such as updating a View after 1 or 2 seconds.
I encourage you to download the RoboSpice Motivations app, it really explains this in-depth and provides samples and demonstrations of the different ways to do some background operations.
If you are looking for an alternative to RoboSpice for non network related tasks (for instance without caching), you could also have a look at Tape.
I believe that AyncTasks are in general still tied to the foreground activity stack that spawned them, so that e.g. if an Activity spawns an AsyncTask, the user leaves the app, and then the OS is short of memory, it will kill the Activity's process (including the still-running AsyncTask), and just expect you to restore the state and start over if the user resumes/returns to your app.
For longer-running tasks, particularly the sort where there will only be only one or a few, you probably want a Service instead, because those can persist even when your app's UI is shut down to save memory.
Disclaimer: I haven't done Android coding in awhile, so this answer may be out of date or based on a flawed understanding of how things work. I will remove this caveat if someone with more recent experience can comment to confirm; high-rep folks are welcome to just edit this paragraph away instead if they know this is correct.

Handling program flow for an application

I am currently trying to write a simple application very similar to this:
http://lab.andre-michelle.com/tonematrix
My main problem is that I do not know how to handle the general program flow. Traditionally, I would use a loop inside the main function that handled the drawing and updated the state and everything. The way the android framework works is a bit confusing since the access points into the program are the various onSomething() functions. This is quite confusing for a beginner.
How do I keep track of time and how do I know how when to move to the next square column?
Do I HAVE to use threads? Is there a single thread solution, similar to the single loop approach?
You can use timers, they do already run in their own threads.
You can also use handlers for timed execution.
In case of the sample program u linked to, you would add something with onTouch and have a timer running in the background to periodically play the tune.
The activity lifecycle should be seen as the lifeline of your program not so much of the code in it.
How to keep track of time ?
System.currentTimeMillis();

Android runOnUiThread - how to pass the Activity

I'm writing a XMPP Client using SMACK.
So when I want to update my contactList - the ListAdapter.notifyDataSetChanged requires to be run in the UI thread, but obviously the SMACK Library uses Multithreading on the RosterListener (which in fact is a good thing). But here is the problem: to run s.th. in the UI thread, I need a valid context.
But how do I get it? Passing the Context of the Activity down to the register function of the RosterListener was the first that came to mind - but I have some functions in different classes there before I even get to the register function, and I don't really like it to pass the context over and over again until it finally reaches its destination, where it will be used.
I guess, I'm not the only one, who has encountered this problem, so how would you solve it?
Maybe a Singleton, just to save this one Context (in my opinion an even less favourable idea...)
Or is maybe my whole design flawed?
Is there a possibility to get the UI thread from anywhere?
Bottom line: I don't really have a clue how to handle it, at the moment I'm passing the context as argument through multiple functions, but is there a better way to do it.
Thanks for any help.
Put XMPP code into Service and then send broadcasts. Interested Activities can simply register for those broadcasts. That way you'll never again worry about UI thread and availability of Activity context.
I found a neater and more modular way of doing it. For this you need to have defined an Application Context. Once you have that, you can call RunOnUIThread from any class library without the mess of having a reference to the Activity.
From anywhere within your class library call:
Handler handler = new Handler(Application.Context.MainLooper);
handler.Post(() => doStuff());
Please bear in mind that this is written in C# as I use MonoDroid, but I believe it is very similar to Java.
For how to create an ApplicationContext look at this thread
I do not get what exactly you try to do but if you are in some thread and you want to shitch back to UIThread than
Looper is your solution
http://developer.android.com/reference/android/os/Looper.html
Reading you, I get a feeling like you are working with callbacks. Smack or whatever that is is calling you back from a worker thread, and you want to post to the main UI thread when that happens.
In my experience, callbacks can always be associated to a custom piece of data, which you pass when registering the callback, and receive when you are actually called back.
In your context there are two approaches which I consider to be poor design:
using any kind of global thingy, call it a singleton if you like
let your Model expect and return the (Android-and-UI-specific) Context
Instead, I would create a small interface which is implemented by the Activity, have the Model accept an instance of this interface, and yes pass it over the different layers until registration.
The methods exposed by this interface will be called asynchronously, which you could document appropriately, to indicate that runOnUiThread() or similar must be used.
This way, you're not exactly passing the Context (which is a platform and UI detail) all over the place and into the Model. Plus, you avoid global/static data, which leads to various problems, conflicts and other memory leaks.

Android app architecture - where to put REST API call code?

I want to better understand how to structure an Android app where an activity fires off an API call (for example).
I'd currently implement it by putting the API call into an AsyncTask subclass, passing it a reference to the activity so it can update the UI in onPostExecute. But my gut-feel is that this is creating overly-coupled code.
I'm wondering whether instead I should put an API call like that into a service, and use a BroadcastReceiver to update the activity.
What say you, AsyncTask, or BroadcastReceiver?
I usually follow the Local Service pattern. I have a strong suspicion that this is how the official Twitter app works and that this is the pattern most of the Google apps use. This also solves the issue of your app going away (getting killed or going into the background) before the task finishes, or if the phone switches configuration during a background task.
BroadcastReceiver and service is an overhead here. A request to web-service should not go to long. Service is appropriate in case of downloading files or something similar.
AsyncTask way is the right one here. But I would suggest you showing a progress dialog to let user know that your application isn't freezed, but doing some useful work.
See the example here.
AsyncTask is just fine. Only thing you should worry about is referencing you Activity using WeakReference to avoid whole Activity be memory leaked. It isn't overly-coupled code imo if you using observer or events patterns.
I would go with a service only if the call is going to take long, so that the user can leave the app while it's completing.
I'd use the AsyncTask if the task is short enough that it almost wouldn't go ANR if done in UI thread.
(disclaimer: I consider myself a beginner, and I'm expecting comments from more experienced people)

Categories

Resources