Should I use a Service as a way of accessing network data?

221 views Asked by At

I'm somewhat new to Android development and I'm trying to build a very simple app which will browse my network for DLNA servers and allow me to browse each DLNA server as a directory. The thought is pretty simple: one activity displays all DLNA servers on the network, user selects one, then we redirect to another activity which browses the DLNA media server's directories.

My question is quite basic: how do I persist information like 'selected server', 'current directory' and other things like this? I just need a way for the rest of my application to know what to do. Should I build this data into a service? It seems like that violates the common understanding of what services should be. How can I/should I persist application state?

1

There are 1 answers

2
Dave MacLean On BEST ANSWER

You have a few options. The one that I think I like the best is that you simply pass these values in the Intent object that you're sending from one activity to the next. Therefore, the activity that browses the DLNA media server's directories receives the selected server in the intent, and if that came from the DLNA list activity, that's great, but the intent could come from any other activity that wants to show media server directories to the user. Try very hard to encapsulate functionality inside an activity so it doesn't need to depend on the rest of the application for data.

When there is data that you really do need across an application, take a look at SharedPreferences. These can be displayable to the user so they can make choices that persist across invocations of your application, and any activity in your application can easily read the preferences and keep current. Not all preferences need to be displayable however. You can always create a preferences editor to read and write your own preferences without ever showing them to a user.

A couple of other options are to setup singleton classes that hold your shared values, and that every activity can refer to, or as a last resort you can extend the Application class, and create getters and setters to make values available across your application. I say last resort because Application is a significant class in Android that's better left alone so you don't accidentally break something now or in the future.

To answer your other question, not only should you use services to do network accesses, but you need to create Threads as well. An Android service does not by default include a background thread, you need to do that yourself. You should never make network calls from the main (a.k.a. UI) thread.