confused between syncAdapter,services,loaders,providers and asynctask? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to android and was going through the documentation and some tutorials.
Services
Developer guide says it should be used, when there is required to run a long running task in background, say music player.
Asynctask
Creates a worker thread to perform background task like getting data using api and then notify the UI thread on it's onPostExecute() callback method.
Loaders
Performs operations on separate thread, registers to the listener and notifies on data set changes.
Providers
Share data between different apps by exposing them in the manifest file.
SyncAdapter
For synchronizing data between android device and web server.
Theoretical wise, i understand the above concepts like what they are used for.
I am having difficulty to put them in order like when to use what? what would be the best among them to use? In what scenarios what should be used?
For caching, i used sqlite or library like volley and retrospice
As i said i am android beginner and try to understand these concepts.
Any helps and suggestions would be appreciated.
Thankx in advance.

A couple of things to add to Kaleb's answer:
ContentProvider:
Android has actually many ways to share data. The ContentProvider is a way to share a database between applications. Let's say you have 3 email clients on your phone that cache data from the cloud in case you're offline. It makes sense that you maintain only one offline database of your emails. The same goes if you have an address book, an sms database, or a tweet database. And the same goes if you want to update all that data. You only really want to update that data only once from the cloud, not three times each time, which brings me to the next topic, the SyncAdapter.
SyncAdapter:
A SyncManager is smart enough to do all the synchronization requests in one go, to minimize the time the antenna is powered, and therefore to save battery use. Furthermore, with the help of the AccountManager, the user of the phone can override the synchronization preferences himself/herself, but that's only if the developer chose to use a SyncAdapter in the first place.
Also, a SyncAdapter can only be used with a ContentProvider. So even if you don't want to share your data with other apps, you'll have to use a content provider if you want to use a SyncAdapter.
That being said, ContentProviders are very hard for beginners (even intermediate developers) to implement. I'd suggest you stay away from them for now. You should use a ContentProvider, if there is already one for what you want to do, but I don't recommend you try to create your own.
Loaders:
Loaders are good. Learn to use them if you want to display data from a local database (or from a ContentProvider). They'll save you time. Unlike the SyncAdapter, loaders do not require a ContentProvider for them to work. They can access SQLite directly.
Services:
Learn to use them. There are too many things to say about them. One important point is that you should minimize the time they stay alive by using components like AlarmManager or BroadcastReceivers. Also, you'll need to learn the difference between a Service and an IntentService.
AsyncTask:
AsyncTask is very often necessary in Android to avoid blocking the main UI thread. Don't think that because you're using an AsyncTask, that you can dispense with the use of Services.
Note that many Android tutorials only give you the minimum amount of code to demonstrate a concept, so they'll often skip proper threading. Note that you can start your own thread manually if you want, but AsyncTask does other things for you that make it the ideal choice for many situations where the UI thread gets blocked and you get an "Application Non Responding" error.
Libraries:
There are many good libraries out there. I won't say which ones are the good ones. Learn to use the ones that everyone recommends. Those libraries can do a lot for you (assuming you're good enough to make them work). There is a bit of a learning curve, but it's worth it. And they deal with Android at a much higher level of abstraction, so usually, the threading and many other things are usually taken care for you.
There are many other things that I am glossing over, or that I didn't mention at all, but like I said, I think your question is too broad. And if you really want more details, you should hunker down and read some the developer guides and watch some of the youtube videos provided by Google.

Really quick answer :
AsyncTask : short task that could block the UI thread. You don't mind if they are cancel and you have to re launch them.
Services : use when you have long task that you don't want to be interupted by App changes. Bit harded to implement than AsyncTask.
Loaders : designed for database access
SyncAdapter : here you don't have realtime data. You schedule data sync at a give moment (i.e sync mails, contact data, etc...). Let's say you have fresh data every hour.
Providers : nothing to do with the above. This is used to share data beetween Apps. You don't care how data is retrieve by the sharing App, you just know that you can ask for a given resource.
This infographis helped me understand better the first 3 : https://raw.githubusercontent.com/stephanenicolas/robospice/master/gfx/RoboSpice-InfoGraphics.png

Related

Is asynchronous threading an option if my GUI relies on data retrieved from a database?

I'm very new to Java's multithreading. I recently found out that a new thread is automatically created when trying to access data from Firestore.
In my mobile application, after the login screen, the GUI relies on data retrieved from Firestore. Is there any way I can benefit from asynchronous threading in this case or am I forced to wait for data retrieval? What's good practice in this case?
Also, I'd highly appreciate it if anyone can provide me with a good source to start getting acquainted with multithreading.
You should always assume data pulled from any online service has an inherent delay and should be handled through async means. as for threading, this is not needed with Firebase as it runs on the main thread.
It is suggested to use template loading models that have gray or loading placeholders until the data is synced to the client, you may see this in other apps as a spinner or a grey box until it loads or times out, which you should also consider if the user is offline.
Firebase manages their own app instance including a local cache for Firestore to help reduce reads and loading time, utilizing a combination of these features with async/await methods will smooth out any issues you may have with rendering data to render with a GUI.

android Java Multiple classes update activity UI (how to share data)

I know this question has been asked several times, but I cannot seems to find a suitable answer or there is multiple solutions. I am just trying to find were to look and the best possible solution.
I have an app that has several activities such as Main, Settings, User profile etc and I have different source for information coming into the app such as pulling data from a server, BLE comms, back ground timer etc. The plan would be to have these calling comms functions in separate classes i.e. servercomms, BLEStack, timer etc
The question what is the best way to share the data from these classes to the activity UI? There seems to be different methods such as Intent, Async, Runable but not sure which one should be used? When I look at one it seems create performance issues and will stop running if the device is short on memory.
For example if there is a Timer running in the background, which will update a picture, text on the Main Activity how can I call a function or update the UI from the timer class? I thought run a function in the MainActvity code, but not sure if that is correct as I read it might affect the mobile app performance?
Sorry, I know this question has been answered and I have followed each thread but just cannot work out the best way to make it all work with sharing data and updating the activity UI.
I'd suggest having look at EventBus as per their description:
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
OR
Have a look at the official android documentation Communicating with fragments which shows how to use ViewModels to share data between activities and fragments and fragment to fragment.

Android/Java decisions about threading

Okay, so I after playing around with the Android SDK a little I have decided to develop a full application. Not necessarily to release on the store (I don't really have the tools at my disposal to do proper QA and so wouldn't feel right; I could only test on my one personal device) it is mostly just a personal project for fun and learning. In the end, I decided on a camera application because I use my camera fairly often so it is the kind of application I would end up actually using if I made it and also because I am quite excited by the features of the new Camera2 API in Android L and want to give them a try.
Anyway, I have been thinking on the design/architecture of the application for a while and I have come across a potential problem that I cannot really resolve myself as I am not only not really familiar with GUI programming of this nature but also not 100% on Java and the Android SDK. They both sit well outside the purview of my dayjob.
Now I know enough that I really need to keep my UI thread separate from everything else, but what I am unsure about is first of all, what I should devote extra threads to (I was thinking one to handle image capture and storage, and another to handle the settings? perhaps that is over doing it) and also whether to have background threads which the UI thread communicates with through Events or simply to spawn threads as and when they are needed. Perhaps a single intermediate background thread which arbitrates between the UI thread and any background processing that needs to be done? What I mean to ask is, how do I decide these things? Are there general/best practices?
I'm really asking because I want to get this done properly and plan out the application thoroughly beforehand since in the past I have found that if I just dive right in I get confused very easily and end up losing faith and dropping the project. I hope somebody can help. It's not a question that I have found easy to phrase in such a way that Google would provide satisfactory results.
I think you might consider thinking about it this way:
The UI thread is where most stuff runs. It is also, occasionally, called the "main" thread, because it is, uhhh... the main thread.
Unless your program is wildly complex, you probably don't need to worry about an architecture for threads. All you need to worry about is getting slow stuff off the UI thread. That's it. You don't care where they go, just not the UI thread.
If you buy that, there are some nifty choices:
Intent Service: If, a bit metaphorically, the methods you need to run in "background" have void return types, an intent service is the perfect solution. You communicate with it using Intents and, since it has only one thread, tasks you submit to that thread are run in order.
AsyncTask: These are fraught with problems but people get a lot of programming done with them. They run in a pool of around 6 threads, but (surprise!) run in order anyway.
Your own Java Executor: Use this if you need behavior similar an AsyncTask, but with more control.
New thread per task: Just don't do this. Really.
In any of these cases, though, you don't really care on which threads your tasks are running. You make a policy about the number of threads that makes sense on the target device and then run your slow stuff on one of them.
...and "slow" should include all I/O: databases, file system, network, etc., as well as major computation.
You want to keep things as simple as possible. You don't need a thread to set settings, and you don't need an intermediary thread. These things are only going to create unnecessary complication. You only need to take long running operations off the UI thread.
Take a look at the structures the Android framework provides to make multi-threading easier first. This will help simplify your application. These would include IntentService and AsyncTask. If those won't meet your needs take a look at the java.util.concurrent package. Using a raw Thread is often not advisable.
Another library that could come in handy is an Event Bus like Otto. This will prevent memory leaks that can occur with using AsyncTask.
You dont need to worry about threads when it comes to image capture. When you want to take a picture you do so by opening the Camera App on the device. Here is a good way of doing that.
Android SDK provides Asynctask which does things for you in the background thread, like a network call and updates the UI once its done.
You can also use an IntentService, which runs even if you exit the app and does things like upload/download without the user having to worry about it. Loaders are useful when the underlying data often changes and you need to update UI quickly (searching contacts in autocomplete text for example).
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
Refer to this tutorial, its a good start. Hope this helps.

Best option for storing data in running application in android [before SQLite]

I'm new to the android development, and programming in general.
I'm developing app to create football statistics for each player, and in the long run I'm using SQLite to store data. However I was wondering if there is a way and if it will make sense, to store data during the run of my application without inserting it to the db, every time user is trying to add new statistics.
Also I'm wondering if there is a point in doing that, my biggest concern is that inserting data to a db all the time will slow down my app, and I would appreciate what more experienced developers do know, and think about this 'issue'
I was trying to research the topic, however all I got was storing data in db, and using SharedPreferences and I don't think that's what I'm looking for, however I can be wrong.
please help.
SQlite is what you're looking for. SharedPreferences are for just that - preferences, not large amounts of stats.
Put your database code in a separate thread and you won't notice any slow down in your app. Ask back here for help on this.
I can't speak to android directly but I have faced similar design issues on iPhone and desktop applications.
It depends on the specifics of the application as to what would be the best way. If your app is mostly about entering plays and saving statistics, I would keep a small set of the latest statistics in memory enough to populate the user interface and then create a "data manager" running on a background thread whose sole purpose was to insert these newly added statistics to the database.
Honestly, I would put it in the DB immediately. With the way android works, if your user navigates to another app (or possibly even receives a phone call) the data they have already entered could be lost.
It is possible to cover that contingency obviously (saving in onPause, etc.), but I've always felt it was safer to get the data into permanent storage as soon as possible. (Note this is a hotly debated topic, I'm merely stating my preference).
Saving to the DB immediately doesn't affect app speed (depending on how much of what type of data you are inserting) so much as battery life. Accessing permanent storage takes more in terms of power as there are several more steps the processor needs to take.
If you do all your DB activities in a thread other than the UI thread the transactions will be almost completely unnoticable in terms of app speed.
If you use implement Loader callbacks it should not slow your application down. Have a look at the Loader classes. They are available through the Android compatibility library.

Need some guidance with multi-app IPC

All I’m really looking for here is a little guidance. I’m trying to create my first official android app. I’m new to java/droid but not programming. Over the past month I’ve created quite a number of little experimental activities, services, threads and whatnot and they all function as planned. So now I’m trying to tie is all together but not having much luck.
In a new project I’ve compiled the guts into 'my.main.package' which runs a service that is constantly crunching data that other clients/apps can use… Well that’s my plan. For example, in this service is a custom thread/loop timer that is constantly counting. What would be the best way for any other apps to get a constant feed of this timer and other data as a listener could within its own sandbox and in the least taxing way possible?
I’m assuming one must implement aidl for IPC but I’m not sure if its needed and/or necessary as data from my.main.package is only outgoing, i.e. other apps only need receive/listen. I understand there needs to be some form of message handling or parcelable marshalling going on and possible permissions with aidl but I got to thinking that encoding/decoding a parcel or sending a message every millisecond would be very taxing. Is aidl the only way to go or is there a way to broadcast data as you can intent?
Any help would be greatly appreciated!
In a new project I’ve compiled the guts into 'my.main.package' which runs a service that is constantly crunching data that other clients/apps can use
A service should only be running when it is actively delivering value to the user. Users think that developers who create services that run all of the time are idiots and attack their apps with task killers, force-stops from the Settings app, etc.
Perhaps your description is just depicting your app in a poor light, but "a service that is constantly crunching data" is an anti-pattern. These are phones and tablets, not servers.
What would be the best way for any other apps to get a constant feed of this timer and other data as a listener could within its own sandbox and in the least taxing way possible?
The best way is for them not to be separate apps in the first place.
For example, in this service is a custom thread/loop timer that is constantly counting.
This is not adding value to the user.
I’m assuming one must implement aidl for IPC but I’m not sure if its needed and/or necessary as data from my.main.package is only outgoing, i.e. other apps only need receive/listen.
A remote service using AIDL is one way of doing IPC. It is not the only way. It is not even the most common way. You can also:
send a broadcast Intent
have the client send a Messenger to the service, and the service sends messages to the client via that Messenger
have the service update a ContentProvider, and have clients register a ContentObserver on the ContentProvider
I understand there needs to be some form of message handling or parcelable marshalling going on and possible permissions with aidl but I got to thinking that encoding/decoding a parcel or sending a message every millisecond would be very taxing.
IPC is "very taxing" in general. Hence, IPC should be avoided wherever possible.
In fact, IPC with AIDL is the only & the most effective way to do your requirements, I think. If you need one demo, you can take a look here. It's a simple example I wrote to learn AIDL & Binder on Android. Hope it could give you some brief for starting.

Categories