Pass context to JobService Android JobScheduler - android

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

Related

Is it good to replace broadcast receiver with Greenrobot Eventbus for triggering event based functions and data transfer from service to activity?

I have implemented a service, where I handle the state changes(connect, disconnect, onServiceDiscoverd, onCharacteristicChange etc) and receiving data from another device through gatt Server.
My question is, Can the events be handled efficiently using Greenrobot Eventbus replacing broadcast receiver between service and Activity?
Unlike LocalBroadcastManager, EventBus is more simple to use. You only go via 3 steps:
1- Create an event class. A simple Java class that represent the response when
the action occur.
2- Register the event bus as a subscriber in your Activity onCreate method
EventBus.getDefault().register(this);
And of course, unregister it in your Activity onDestroy method
EventBus.getDefault().unregister(this);
3- The subscribing method is created in the same activity that registered for the EventBus. Example in WorkOrderActivity
#Subscribe
public void onEvent(EventClass event)
When the event occur, you should call the post method, passing the event object you created before.
EventBus.getDefault().post(new EventClass (Data));
As kmaini mentioned, you can replace it with LocalBroadcastManager, but you will have to map the data from the intent by yourself. Unlike EventBus which can pass objects.
Also, greenrobot, the creators of EventBus Library, answered this question here:
Q: How's EventBus different to Android's BroadcastReceiver/Intent
system?
A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses
standard Java classes as events and offers a more convenient API.
EventBus is intended for a lot more uses cases where you wouldn't
want to go through the hassle of setting up Intents, preparing Intent
extras, implementing broadcast receivers, and extracting Intent
extras again. Also, EventBus comes with a much lower overhead.
From another perspective, I believe broadcast managers in Android uses main thread handler's message queue to process events. So, if you are free to use a different thread (if you have no-UI events/jobs/tasks) with a proper queue (like using another HandlerThread) then you can take advantage of using that thread's specific queue to process your jobs, without interfering UI events and mixing your stuff with UI work. You can also play with the thread's priority value to balance the work.
Now, if GreenRobot provides that all functionality in a few lines of code, then I would definitely try it to see any performance gain.
EventBus makes things much easier because you can pass is arbitrary Java objects along in the event.You not do the same with Intents because your object has to implement Parcelable and the "tedious" parcelable implementation which is something you might not what to do on an existing code base.

how to findViewById in a Service Class in android

I have a class that extends service and the service basically fetches data from the cloud and lists ot in a listview..am getting an error when i try to use "findviewById" method to get the listview because the class doesn't extend Activity.does anyone know how i should go about it.
Your service cannot modify the UI directly. In fact, there may not be a UI at all, as the user may have pressed BACK and destroyed the activity while the network I/O is going on.
Instead, you need to send a message from the service to the activity to let the activity know, if it exists, that there is new data. For this, you can use:
LocalBroadcastManager from the Android Support package, or
a third-party message bus implementation, like Square's Otto, or
a Messenger tied to a Handler
etc.
Hi There in my opinion better to use the AsncTask in that you have to write the backend downloading data part in doinBackground method and setting the data to the list view in onPostexcute.
Better have a look into the asynctask
http://developer.android.com/reference/android/os/AsyncTask.html
mean while try to bind a service and make communication from service to activity for this have a look into how to bind a service.
for binding a service
http://developer.android.com/guide/components/bound-services.html

Google IO 2010 Rest Structure

I am looking to implement the Google IO Rest Structure part A - Using a Service API. So i have identified the following portions of the structure.
An interface that provides rest method.
A Processor Class that implements the above interface. There will
many processor Classes. Each Processor class will return a model
class type.
A Service Provider, that deals with a Single Processor. The data
returned from the Processor is handled by the Service Provider. This
will call the Processor Function, and obtain the data returned.
A SerivceProcessor that is a service class. There will be a
single class in the application. This will communicate with the
various SericeProvides based on the Bundle data passed to it.
Service helper that provides high level integration between the
Activity and the Service
Now i am not clear here. The Service has the data that has been requested. How to proceede further. How do i pass the data back from the Service to the ServicHelper. Put it in a Bundle with the tag BUNDLE_EXTRA ? For this my pojo would have to be either Serializable or Parceable. I know Serializable is a really bad option on the Android Platform. What other options are they. Would i be using a Broadcast Intent ?
Thanks for any help here.
You can do a couple of things.
notifying back to the service helper through intents (letting it implement a broadcast receiver). This might be a bad idea since with a single rest call you can get a lot of rows. In this case you should implement some sort of facility to put your pojos in the intents you are sending back (like a fillIntent/getFromIntent method)
inside the service provider, store the result data somewhere (sqllite, contentprovider, file) and just throw a broadcast intent that will contain only the requestId and the result of your call.
The service helper intercept the broadcast and notifies any interested activity that the request has been completed. The activity updates the ui according to that. In this case the servicehelper is used just to keep track of the ongoing request / notify the results.
In my opinion this approach is better because you keep the ui and the model separated, and you don't demand to the activity the storage of the data, and it's more "rest oriented".
Plus: some time ago I tried to implement this approach. It's not completed but you can check the service helper and the request / result intents here postman lib
A more mature and robust library is robospice, which is what I would use now if I had to deal with rest services.

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

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.

Sync between local service with a thread and an activity

I'm trying to think of a way on how to sync in between a local service and the main activity.
The local service has,
A thread with a socket connection that could receive data at any time.
A list/array with data.
At any time the socket could receive data and add it to the list.
The activity needs to display this data. So when the activity starts up it needs to attach or start the local service and fetch the list. It also needs to be notified if the list is updated.
I think I would need to sync my list somehow so the local service does not add a new entry to it while the activity fetches the list when connecting to the service.
Any ideas?
Thanks.
I answered a somewhat similar question here. In this answer is a link to a presentation hold by mark brady on the droidconf in berlin. In his slides he describes a framework that manages this kind of things. He also offers the source for this on github.
He proposes the following solution. Build a controller object that lives in the scope of an custom application class. The controller starts the service or a simple worker thread and notifies the UI if it gets notified by the service that something changed. He advises against the use of AIDL if it is not absolutely necessary.
The android documentation also offers an example on how to start a local process.
There are many ways to establish connection between an activity and a service and share data between them. You can communicate using following solutions:
Intents. You can send ( by sendBroadcast (Intent intent) and receive ( by BroadcastReceiver ) Intents. Example scenario: Your activity at boot moment send a broadcast "GIVE_ME_ALL_DATA" and the service sends a response. If the service has new data, it also broadcasts "HEY_I_HAVE_NEW_DATA".
ContentProvider. The service and the activity read and write parallel from it. You can attach observer to specific data-url, so every listener will be informed about changes. If You use CursorAdapter for binding data to ui components, user interface will be updated automatically.
AIDL. It's a android'a IPC. You define interface for the service which be exposed to clients. Client at the beginning: establishes connection with the service, asks for data, register call-backs. If the service has new data, it invokes call-backs registered by clients.

Categories

Resources