1+ public class LocalService extends Service {
2+ // Binder given to clients
3+ private final IBinder mBinder = new LocalBinder ();
4+ // Random number generator
5+ private final Random mGenerator = new Random ();
6+
7+ /**
8+ * Class used for the client Binder. Because we know this service always
9+ * runs in the same process as its clients, we don't need to deal with IPC.
10+ */
11+ public class LocalBinder extends Binder {
12+ LocalService getService () {
13+ // Return this instance of LocalService so clients can call public methods
14+ return LocalService .this ;
15+ }
16+ }
17+
18+ @ Override
19+ public IBinder onBind (Intent intent ) {
20+ return mBinder ;
21+ }
22+
23+ /** method for clients */
24+ public int getRandomNumber () {
25+ return mGenerator .nextInt (100 );
26+ }
27+ }
28+
29+ //start service
30+
31+ public class BindingActivity extends Activity {
32+ LocalService mService ;
33+ boolean mBound = false ;
34+
35+ @ Override
36+ protected void onCreate (Bundle savedInstanceState ) {
37+ super .onCreate (savedInstanceState );
38+ setContentView (R .layout .main );
39+ }
40+
41+ @ Override
42+ protected void onStart () {
43+ super .onStart ();
44+ // Bind to LocalService
45+ Intent intent = new Intent (this , LocalService .class );
46+ bindService (intent , mConnection , Context .BIND_AUTO_CREATE );
47+ }
48+
49+ @ Override
50+ protected void onStop () {
51+ super .onStop ();
52+ // Unbind from the service
53+ if (mBound ) {
54+ unbindService (mConnection );
55+ mBound = false ;
56+ }
57+ }
58+
59+ /** Called when a button is clicked (the button in the layout file attaches to
60+ * this method with the android:onClick attribute) */
61+ public void onButtonClick (View v ) {
62+ if (mBound ) {
63+ // Call a method from the LocalService.
64+ // However, if this call were something that might hang, then this request should
65+ // occur in a separate thread to avoid slowing down the activity performance.
66+ int num = mService .getRandomNumber ();
67+ Toast .makeText (this , "number: " + num , Toast .LENGTH_SHORT ).show ();
68+ }
69+ }
70+
71+ /** Defines callbacks for service binding, passed to bindService() */
72+ private ServiceConnection mConnection = new ServiceConnection () {
73+
74+ @ Override
75+ public void onServiceConnected (ComponentName className ,
76+ IBinder service ) {
77+ // We've bound to LocalService, cast the IBinder and get LocalService instance
78+ LocalBinder binder = (LocalBinder ) service ;
79+ mService = binder .getService ();
80+ mBound = true ;
81+ }
82+
83+ @ Override
84+ public void onServiceDisconnected (ComponentName arg0 ) {
85+ mBound = false ;
86+ }
87+ };
88+ }
0 commit comments