Howto in Android: Model inside service, accessed by multiple activities - android

I have a service that connects to a server (regular TCP socket) and receives data updates in a thread. I want to store this data (after a bit of processing) in a model that can be accessed by multiple activities (typically ListView with custom ArrayAdapters). In the activities I use bind to get a handle to the service so that it can access the model and register as a listener to get notifications when the model change.
The problem is that access to the model needs to be thread safe. First I thought I would call runOnUIThread with the incoming data inside the service for updating the model, but the service does not have that routine. Any other way to update the model inside service from the UI thread? Or is there a better architecture/pattern that I should use?

No response, but this is what I ended up with: Every on... call (e.g. onCreate, onBind etc) are run on UI thread, so I ended up creating a handler in onCreate and posting to that handler to update my model on the UI thread.

Related

Pass context to JobService Android JobScheduler

I am building an app where I store the url and Json in my local SQLite db and then schedule a JobService.
In the JobService, I take out all the requests one by one from the db and execute them. Once they are executed, I get the response inside the JobService only. Now my real problem is how do I send the response back to the user from the service.
I thought of implementing a callback/listener in activity and passing the value in listener object inside the service. But I am taking out the requests from the SQLite db. So I don't know how to save the callback instance or the context inside my database so that I get that with the rest of the data inside the service itself.
Any ideas?
One approach is to use an event bus implementation: LocalBroadcastManager, greenrobot's EventBus, some Rx-based bus, or even a simple MutableLiveData singleton. Have the service post a message on the bus. Have your UI layer register and unregister from the bus as they come and go. Have the UI layer process messages received on the bus, and have the service raise a Notification if the UI layer does not pick up the message.
Here are sample implementations using:
LocalBroadcastManager: https://github.com/commonsguy/cw-omnibus/tree/v8.6/EventBus/LocalBroadcastManager
greenrobot's EventBus: https://github.com/commonsguy/cw-omnibus/tree/v8.6/EventBus/GreenRobot3
MutableLiveData: https://github.com/commonsguy/cw-androidarch/tree/v0.1/General/LiveBus

creating a call back for AsyncTask in a model to update an activity

I'm creating an app in an MVC pattern... and I'm trying to do most of the data getting and manipulation on the Model side of things so I don't clutter up the Activities with code that does not belong there, but the one thing that's tripping me up a bit is AsyncTask... from what I've seen it seems that this is called most of the time in the UI because it allows you to update. the problem with that is I am doing all my network calls using AsyncTask from my model not my activity. But I still want to update my UI when cretin things happen such as a network call returned something put it in the ui.. so is there a way to make a call back from a model to the Activity or something to that effect, so I don't have to put that code in the activity?
any help would be greatly appreciated.
What you need is an interface which acts as an update "listener" in your Model. That way, your activity can register with the listener when it is active and receive notifications of changes accordingly.
There are many examples (and built-in listener classes) - here is one:
http://www.tutorialspoint.com/java/java_interfaces.htm
Creating an interface in your Activity that is registered in your model allows your model to notify the interface of changed data in order to update properly. If you implement your model as a service or maintain instances of them in a service, then you can bind to the service and then register your listener assuming your model processing extends beyond the life of activities.
If not, AsyncTask is where model processing should occur and you can implement your model synchronously and use listeners to monitor it.

android request http data in common thread and return the string to ui thread

I need to write a common class for handling http request in the background thread ..i have 4 diffrent ui activities which all wants use the same class to fetch web data and update in their activity... My ui activity wants to just call background class and it should not wait for data..background class only need to post the datato ui thread then ui thread will handle that data... I tried using Asynch task...but it works when i implemented in the same ui class... Can some one give better approach to implement in common class ..and also I have confused between which one to go with asynch task or handler with runnable thread...
Write a service that runs in the background and polls the server for data (use an AsyncTask or some sort of thread to perform the query asynchronously). When data is received from the server, insert it into a local database (a ContentProvider backed by an SQLiteDatabase, for example). Then have the Activity query the local database whenever it needs new data. The advantage here is that you will still be able to display data even when your device is offline... the local database acts as a cache that holds previously-queried data.
As far as I understand AsyncTask has everything you need. Just implement its heir as a standalone class and then use it in your activities.

Separate Threads for UI and Logic - Android

I want to create separate threads for implementing the core logic and updating the GUI.
Both threads should not share data with them directly. For this, i want to create a vector queue with synchronized get() and put() methods.
Suppose if an onClick event happens in the GUI thread, it notifies the core thread that it received the OnClick event. So the core thread implements something and puts the result in the vector. At this point, the GUI thread is notified of the received result and it fetches it and updates the screen.
I cant figure out how to do this. Is there a way this could be implemented?
You can do that as you would in any other framework or environment. The Android api offers you a lot of high level ways of handling multithreaded applications like you described (AsyncTask, Handler/Thread/Runnable, etc), but you can also wrap these in your own processing queue. I've done that recently where I created a logical queue for processing, and when I push something to the queue, I run a method that checks my queue for items and processes them on a background thread. You can notify the system when your processing is complete by sending broadcast intents and registering IntentFilters at the Activity level (don't forget to unregister) or you can implement your own listener interfaces the way the Android UI framework does with UI events on Views
At the heart of it though, however you wrap it, AsyncTask makes it really easy to call back and forth between background threads and the main UI thread. onPreExecute, onProgressUpdated and onPostExecute all run on the UI thread and doInBackground runs in a background thread that is automatically created for you. Doesn't get any easier than that

Do I need a handler?

I am working on an Android application and I have a question. I have a listener class that runs on back ground periodically and get data from my server. I want to add that data into a data structure in the main thread. In this case, I am not touch the main U.I. but I was wondering if I should use a handler to add the data into the data structure in the main thread. Or can I just set the data structure as static and access from the listener class to insert the data. Which way should I do? Thanks in advance.
One way to do that (but there are others) is to use a list view and a cursor (it means you should use a database).
When you receive data from server (in your background thread), you add them to the database.
On the UI thread, you register a ContentObserver to be notified when data is added. When you're notified, you just have to requery
If you don't want to use a database, you can then send a Broadcast (see BroadcastReceiver) in which you can add data.

Categories

Resources