开发者

How to turn an activity into a service in android?

I am new to android and I have written a program that displays the location of the android user and also sends it via a web service to a server. In my application I wanted this to run in the background while a list of names and other processes are going on the screen. I have 开发者_高级运维searched this and found that a service can be run in the background and I was wondering if anyone had any suggestions on how to turn this into a service?


A service would not be the best use for this. Services run in the background, but they run on the same thread as the main UI thread of the application. This is fine if the user is not directly interacting with the application. For example, if you have an app that loads a file to a server, you can have a button that starts the service to load the file and close the activity for the app while the service continues to run in the background. Once the file is loaded, you can pop up a notification that the file was loaded or just shut the service down.

Service that run while the activity is running in the foreground can block the activity. Thus, you don't want to use a Service for this purpose as the UI won't update while a service is downloading or uploading something to a server

What you want is an AsyncTask. AsyncTask is a one-shot thread handler that allows you to do high-intensive work while updating the UI.

http://developer.android.com/reference/android/os/AsyncTask.html

If you want to do this continuously, then AsyncTask may not work. In this case, you can use Java timers or standard Java threads to handle continuous work. Just note that you NEVER want to update the UI from any other thread than the UI thread. It will make your app crash eventually.


Read the Service class documentation in the SDK, it has all you want to know plus examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜