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

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.

Related

How much overhead is associated with an Android Fragment?

In Android land, Fragments are aware of the Android lifecycle and are not destroyed when an activity is recreated. Because of this, I have seen people using empty fragments to get around issues with the Android lifecycle destroying references to background tasks and prevent leaks associated with keeping references to activities.
I was wondering how much overhead is associated with using Fragments as hooks to background tasks? I assume that Android decides not to destroy fragments because they are expensive to recreate (could be wrong).
Bonus question. Is there a way we can measure this cost? (maybe implementing alternate methods and checking resource utilisation).
You should not use a 'headless fragment' for background work.
The correct way is to use a Loader or Service (or Intent Service) depending on the duration and type of work that needs to be done.
In terms of overhead, I don't think there is much. You can create 4 apps with these 4 methods and profile them if you want, but the better approach is to pick a method that works for the problem you are trying to solve.
Do not use Fragments to keep tasks alive!
That will do more harm than use.
If you have tasks running long enough that you have to worry if they get killed, run them in a Service.
This is exactly what a Service (or Loader) is for. Fragments should represent a part of your layout, not be used headless.
There is no reason to hack around if a working and intended solution exists.

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

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

Best way to implement Socket.io in android

I am planning to implement Socket.io in android by this library for a chat based application. As far as I understood the library seems to be pretty good. I want to know how to maintain a single socket connection throughout the app all the time? Here I have listed out ways to achieve, in which I need the best and stable way.
Three ways
MainApplication Class extends Application
By this we have a good scope that the socket connection is maintained in the main thread( or application's life cycle) and whenever the socket instance is needed from the activity we can get it easily. But it's main thread which also the problem. It might block the main thread.
BoundService
By this way we can bind the service with the activities and we can simply use it. Doing in separate thread is the way to achieve IO/Network calls. But cross processing transfer is more expensive than directly accessing in same process.
Singleton
Maintaining connection in Singleton also makes sense. But we don't know when the instance is killed by process, because it doesn't work in activity life cycle.
If I makes sense please help me out. If not comment it out.
Edit
I have given the answer which is more suitable for me.
First of all, the Application's onCreate() is irrelevant in your use case because you can't have a thread running in the background when it was first initiated in a non service code.
Also, I would recommend using Google Cloud Messaging instead of creating your own mechanism. It would be best for the device's battery life and much less code for you to handle.
If you do want to implement that chat completely on your own, Service is your only choice. You can also combine it with a singleton, but I wouldn't recommend that approach. You can use broadcasts and BroadcastReceiver for communicating between your Service and Activity, I think it is easier than a Bound Service since bounding to the service is asynchronous and it creates a lot of mess compared to simple broadcasting.
Service for Maintaining socket connection
As per Ofek Ron mentioned Service with BroadcaseReceiver is a better idea than BoundService. Because its a tedious process to maintain communication. And I also recommend pub/sub way of broadcasting, like Otto or EventBus (I myself suggest Otto by Square, which is clean and brilliant api).
Pros of OTTO
1. Cleaner Api
2. You can subscribe and publish in/to any Activity, Fragment, Service class.
3. Decoupling. (You have to couple as less as possible in your code).
And one more point is use START_STICKY in the onStartCommand() to start service after it is getting destroyed. See this reference.
MainApplication to start the service
It's best practice to start the service in the MainApplication that extends Application. Because the application will be killed when there is a memory constraint or user forcefully closes the app from the stack. So onStartCommand() will not be called frequently like if we have implemented in Activity.
Implementing online status
You can implement online status simply by implementing Application.LifeCycleCallbacks in the MainApplication class, which has most of the life cycle callbacks of activity and will be notified in the callback. By that you can implement Online status simply without any boiler plate codes. (If anyone need help here let me know).
Uploading or downloading images or files.
Best practice is to implement by IntentService because it's running in the a separate thread. I promise which will give the best performance because it is handled by android itself, not like threads created by us.
You can combine first way and third way like:
Create Sockets in your Application and declare them as static. So you can maintain and access them every where in you application. Don't forget to create separate Threads to perform the network operations, you can use ThreadPool to manage those Thread. If you want to update your UI from those Thread you can use Handler and Message to communication with UI Thread
Before you create your own implementation of a socket.io client, you should give this library a chance: https://github.com/socketio/socket.io-client-java
I use it in one of my projects to communicate with a node.js server which is working pretty fine. Actually, all of your suggestions are correct and mostly depend on what you want to achieve. However, one context is always available: the application context. Therefore you should keep a singleton instance in the Application class and get it by getApplicationContext().
Online status of the user: here you should create a background service which is listening constantly for the users state. As there are not many information, this should be okay and should not drain the battery too much. Additionally you can send a flag if there are new information available and only if there is something new, you start another thread, which is receiving the new data. This keeps the data low.
Chat: the chat data is transfered only when the app is active. So, this should be done in an activity.
Both the service and the activity can access the singleton instance of the socket.io client from the application context. As long as you do not process any complex data on the main thread everything is fine. So, wrap your calls into separate thread and only start them when they are actually needed.

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.

Android: Preventing long-initializing app from being killed

I've been working on an app, and it's came long great. I have a problem though, Android, being greedy with its resources, loves to kill the app when I put it in the background. This is very bad, because the app is actually intended to be an AI assistant, and having to reinitialize every-time I need to use it means that it's not going to be very helpful in a real work environment.
I investigated ways to prevent reinitialization of the AI's brain, however, none of the methods have been very fruitful. Saving the instance of its brain will not work, because the POS models that she needs to operate can't be serialized. And employing a service won't work either, because if I want to communicate with the activity via the service, I have to reinitialize it along with the activity (correct me if there is a way around this, I just notice most tutorials put service.start() in the onCreate methods)
Is there a way around this? I only need to preserve the POS models. They take a while to load in for some reason despite only being a few megabytes.
Please note that this is to prevent data from being killed. There are no background processes that need to be ran.
You need to set a Notification to tell Android not to release your resources.
See this question: How can we prevent a Service from being killed by OS? . While the question itself is not directly applicable the answers have a lot of overlap with this issue.
You should probably be using a Service if you want to run things in the background though as Activities are only supposed to run when you have a layout in the foreground. You could store your required object in the service, grab it as necessary when (re)starting an Activity that requires it and update it when your Activity loses focus.
Edit: I accidentally pasted the wrong link. Now corrected.
Also, have a look at this Android resource if you have not already: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Categories