Changes

Jump to: navigation, search

Android 6 Local Bound Services – A Worked Example

15 bytes added, 20:04, 27 October 2016
m
Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">"
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
}
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
Having made the changes to the class, it is worth taking a moment to recap the steps performed here. First, a new subclass of Binder (named MyLocalBinder) is declared. This class contains a single method for the sole purpose of returning a reference to the current instance of the BoundService class. A new instance of the MyLocalBinder class is created and assigned to the myBinder IBinder reference (since Binder is a subclass of IBinder there is no type mismatch in this assignment).
</manifest>
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
The next phase is to implement the necessary code within the activity to bind to the service and call the getCurrentTime() method.
All that remains is to implement a mechanism for calling the getCurrentTime() method and displaying the result to the user. As is now customary, Android Studio will have created a template activity_local_bound.xml file for the activity containing only a TextView. Load this file into the Designer tool using Design mode, double-click on the TextView component and change the ID to myTextView. Move the TextView to the center of the display canvas, add a Button view beneath the TextView and change the text on the button to read “Show Time”, extracting the text to a string resource named button_string. On completion of these changes, the layout should resemble that illustrated in Figure 44-1:
<googlehtmlet>ADSDAQBOX_FLOWadsdaqbox_flow</googlehtmlet>
[[Image:android_studio_local_bound_ui_1.4.png]]
</RelativeLayout>
</pre>
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
Finally, edit the code in the LocalBoundActivity.java file to implement the showTime() method. This method simply calls the getCurrentTime() method of the service (which, thanks to the onServiceConnected() method, is now available from within the activity via the myService reference) and assigns the resulting string to the TextView:
<googlehtmlet>BUY_ANDROID_STUDIO6androidstudio_a6</googlehtmlet>
 
<htmlet>ezoicbottom</htmlet>
<hr>
<table border="0" cellspacing="0" width="100%">

Navigation menu