Changes

Jump to: navigation, search
m
Text replacement - "<google>BUY_ANDROID_STUDIO6</google>" to "<htmlet>androidstudio_a6</htmlet>"
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
}
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
All that remains at this point is to implement some code within the onHandleIntent() method so that the service actually does something when invoked. Ordinarily this would involve performing a task that takes some time to complete such as downloading a large file or playing audio. For the purposes of this example, however, the handler will simply output a message to the Android Studio LogCat panel:
</manifest>
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
== Starting the Service ==
For the purposes of this example, a new class will be added to the project that will subclass from the Service class. Right-click, therefore, on the package name listed under app -> java in the Project tool window and select the New -> Service -> Service menu option. Create a new class named MyService with both the Exported and Enabled options selected.
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
The minimal requirement in order to create an operational service is to implement the onStartCommand() callback method which will be called when the service is starting up. In addition, the onBind() method must return a null value to indicate to the Android system that this is not a bound service. For the purposes of this example, the onStartCommand() method will loop three times performing a 10-second wait on each loop. For the sake of completeness, stub versions of the onCreate() and onDestroy() methods will also be implemented in the new MyService.java file as follows:
As demonstrated in the previous section, any component that undertakes a time consuming operation on the main thread will cause the application to become unresponsive until that task is complete. It is not surprising, therefore, that Android provides an API that allows applications to create and use additional threads. Any tasks performed in a separate thread from the main thread are essentially performed in the background. Such threads are typically referred to as background or worker threads.
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
A very simple solution to this problem involves performing the service task within a new thread. The following onStartCommand() method from the MyService.java file, for example, has been modified to launch the task within a new thread using the most basic of thread handling examples:
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>

Navigation menu