START A SERVICE IN ANDROID

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
 651  View(s)
Ratings:
Rate this:
Suppose that you are starting a service in an Activity as follows:
Intent service = new Intent(context, MyService.class);             
startService(service);
where MyService accesses a remote server via an Internet connection.

If the Activity is showing an animation that indicates some kind of progress, what issue might you encounter and how could you address it?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Start a service in android

    Responses from a remote service via the Internet can often take some time, either due to networking latencies, or load on the remote server, or the amount of time it takes for the remote service to process and respond to the request.

    As a result, if such a delay occurs, the animation in the activity (and even worse, the entire UI thread) could be blocked and could appear to the user to be “frozen” while the client waits for a response from the service. This is because the service is started on the main application thread (or UI thread) in the Activity.

    The problem can (and should) be avoided by relegating any such remote requests to a background thread or, when feasible, using an an asynchronous response mechanism.

    Note well: Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!