how to findViewById in a Service Class in android - 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

Related

Interface between service and activity

I have a service bound to an activity. I defined an interface that is implemented by the activity. In the service I have an object of the interface that implements the activity, i give memory to this object when I call the method that returns the binder.
The service implements socket.io when I receive a message from the server, I call the interface method to update data in the activity.
My question is, am I using bad practices? Should I implement a LocalBroadcastReceiver to communicate with the activity instead of using the interface?
what do you suggest me?
Short answer is yes it is really a bad practice.
Long answer, even though you reference your activity over an interface it's still the same object in the memory. So let's say you have long running operation on your service then when the activity is recreated after a rotation or any kind of configuration change your old reference will be kept in the Service and it will be leaked.
So since your question is too generic I can just list the alternative methods, you can look through all of them and apply whichever fits on your style.
EventBus (Publish/Subscribe pattern, the easiest solution)
Dependency Injection (Use Dagger or similar to inject your model on
both Activity and Service
BroadcastReceiver
Messenger

Performing Request After Android Service Binding

I have a two part question. Both are somewhat general.
I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.
Hopefully that wasn't too abstract. Thanks in advance.
Yes, Service is the way to go, but a started service, not a bound one.
You could make async request methods, and the Service can broadcast the result back to your Activity.
The async request in this case is a startService(intent) with an
Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
And the reply is a broadcast by the Service with the relevant data.
This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.
To start, you should get yourself familiar with these topics:
Started Services (for the requests)
LocalBroadcastReceiver (for the reply)
Event Bus (alternative to LocalBroadcastReceiver, for example Otto)
I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!
1)If you need code to run even when your Activity isn't, the correct answer is a Service. If you just need to cache data, then storing it in a global static variable somewhere may be ok.
2)Your service can start a Thread or AsyncTask. These execute in parallel. onStartCommand generally launches it in this case.
As with most things, the answer to these questions are subjective at best. I would need more information then I currently have, but I'll take a vague, general stab at this...
If you need something persistently hitting your server repeatedly I would say use a service.
Where you call it is not nearly as important as how many times it needs to be called. That being said the answer is yes. If you need this data as soon as the application or activity loads, then the onCreate method is where it needs to be loaded.
My reccomendation is either A) service or B)AsyncTask.
Go with A if you have to hit the server repeatedly for data and need it in regular intervals. Otherwise go with an AsyncTask and load all the data you need into an object for storage. Then you can use it as you need and it will essentially be "cached".
The difference between the two is simply "best tool for the job". I see you use some javascript. To give a proper analogy, using a service for a server call rather than an async task, is the equivalent of using a web socket (node js) when you could of just used an ajax call. Hope this helps. Oh and PS, please don't use static variables in Android =).

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:How to get call backs from service to activity?

I am using a service to upload a file to server and I am getting some result after file uploaded I want some call backs from service like when upload completed, when got result, if didn't got result in specific time, when network lost etc. as per these call backs I need changes in my activity from where my service was called. currently I am using different-different broadcast send and receive like this.
Intent w = new Intent("<KEY>");
w.putExtra("***", ***);
sendBroadcast(w);
It is working fine now but I want to know that it is proper way to do such or is there any better way?
I also red about pass Handler from activity and pass message queue from service but I am not comfortable this.
Using BroadcastReceivers is perfectly fine.
But if your worker upload-thread needs to run once-off time, then an AsyncTask may better suits your needs. You do your work in doInBackground and then use onPostExecution() to update your GUI.
As you said, you can also use a Handler inside your Activity. But then your Service will need to be a bound Service in order for you to be able to pass the Handler to the Service.
For very simple things, I'd advise you to use an AsyncTask.

How to get updated information from a Service?

I am writing an Android app, API Level 10.
I have a main activity that starts a service and puts a parcel containing a class object as an extra for the service intent. Events that the service handles updates the information stored in the class object. How can I access the new class object from the main activity? Is there a way to send an intent or message to the main activity?
Thanks in advance. I have been kinda vague so if you need clarification please let me know.
Yes, Android provides Handlers to do what you need to do. Please read this documentation http://developer.android.com/reference/android/os/Handler.html
Keep in mind though, that a Handler will only be able to handle String messages so what you can do is have a copy of the class object in your main activity and then keep modifying that object using the messages received by the handler (do conditional checking for each type of message and modify the object accordingly). Does this make sense?

Categories

Resources