forked from hussien89aa/AndroidTutorialForBeginners
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindService.java
More file actions
Latest commit
88 lines (76 loc) · 2.68 KB
/
Copy pathbindService.java
File metadata and controls
88 lines (76 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
publicclassLocalServiceextendsService {
// Binder given to clients
privatefinalIBindermBinder = newLocalBinder();
// Random number generator
privatefinalRandommGenerator = newRandom();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
publicclassLocalBinderextendsBinder {
LocalServicegetService() {
// Return this instance of LocalService so clients can call public methods
returnLocalService.this;
}
}
@Override
publicIBinderonBind(Intentintent) {
returnmBinder;
}
/** method for clients */
publicintgetRandomNumber() {
returnmGenerator.nextInt(100);
}
}
//start service
publicclassBindingActivityextendsActivity {
LocalServicemService;
booleanmBound = false;
@Override
protectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protectedvoidonStart() {
super.onStart();
// Bind to LocalService
Intentintent = newIntent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protectedvoidonStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Called when a button is clicked (the button in the layout file attaches to
* this method with the android:onClick attribute) */
publicvoidonButtonClick(Viewv) {
if (mBound) {
// Call a method from the LocalService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
intnum = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
privateServiceConnectionmConnection = newServiceConnection() {
@Override
publicvoidonServiceConnected(ComponentNameclassName,
IBinderservice) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinderbinder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
publicvoidonServiceDisconnected(ComponentNamearg0) {
mBound = false;
}
};
}