2
3
import android.os.Bundle;
4
import android.os.IBinder;
5
import android.app.Activity;
6
import android.content.ComponentName;
7
import android.content.Context;
8
import android.content.Intent;
9
import android.content.ServiceConnection;
10
import android.view.Menu;
11
import android.view.View;
12
import android.view.View.OnClickListener;
13
import android.widget.Button;
14
import android.widget.Toast;
15
import android.widget.SearchView.OnCloseListener;
16
17
public
class MainActivity
extends Activity
implements OnClickListener, ServiceConnection {
18
19
private Button btn_start, btn_stop, btn_bind, btn_unbind,btn_getNum;
20
private Intent servicesIntent;
21
private EchoServices echoServices;
22
23 @Override
24
protected
void onCreate(Bundle savedInstanceState) {
25
super.onCreate(savedInstanceState);
26 setContentView(R.layout.activity_main);
27 btn_start = (Button) findViewById(R.id.btn_start);
28 btn_stop = (Button) findViewById(R.id.btn_stop);
29 btn_bind = (Button) findViewById(R.id.btn_bind);
30 btn_unbind = (Button) findViewById(R.id.btn_unbind);
31 btn_getNum = (Button) findViewById(R.id.btn_getNum);
32 btn_start.setOnClickListener(
this);
33 btn_stop.setOnClickListener(
this);
34 btn_bind.setOnClickListener(
this);
35 btn_unbind.setOnClickListener(
this);
36 btn_getNum.setOnClickListener(
this);
37 servicesIntent =
new Intent(
this, EchoServices.
class);
38 }
39
40 @Override
41
public
void onClick(View v) {
42
int id = v.getId();
43
switch (id) {
44
case R.id.btn_start:
45 startService(servicesIntent);
46
break;
47
case R.id.btn_stop:
48 stopService(servicesIntent);
49
break;
50
case R.id.btn_bind:
51 bindService(servicesIntent,
this, Context.BIND_AUTO_CREATE);
52
break;
53
case R.id.btn_unbind:
54 unbindService(
this);
55
break;
56
case R.id.btn_getNum:
57
if(echoServices!=
null){
58 System.out.println(echoServices.getCurrentNumber());
59 }
60
61
break;
62 }
63
64 }
65
66
/**
67
* 當服務綁定成功時觸發
68
*/
69 @Override
70
public
void onServiceConnected(ComponentName arg0, IBinder binder) {
71 Toast.makeText(getApplicationContext(), "綁定成功", 1).show();
72 echoServices=((EchoServices.bindServices)binder).getEchoServices();
73 }
74
75
/**
76
* 當綁定失敗時觸發
77
*/
78 @Override
79
public
void onServiceDisconnected(ComponentName arg0) {
80 Toast.makeText(getApplicationContext(), "綁定失敗", 1).show();
81 }
82
83 }
4.oncreat、onbind、ondestroy、onunbind方法的區別app
採用Context.bindService()方法啓動服務,在服務未被建立時,系統會先調用服務的onCreate()方法,接着調用onBind()方法,這個時候訪問者和服務綁定在一塊兒。 若是訪問者要與服務進行通訊,那麼,onBind()方法必須返回Ibinder對象。若是訪問者退出了,系統就會先調用服務的onUnbind()方法,接着調用onDestroy()方法。若是調用bindService()方法前服務已經被綁定,屢次調用bindService()方法並不會致使屢次建立服務及綁定(也就是說onCreate()和onBind()方法並不會被屢次調用)。若是訪問者但願與正在綁定的服務解除綁定,能夠調用unbindService()方法,調用該方法也會致使系統調用服務的onUnbind()-->onDestroy()方法。ide
Activity與服務進行通訊,開發人員一般把通訊方法定義在接口裏,而後讓Ibinder對象實現該接口,而Activity經過該接口引用服務onBind()方法返回的Ibinder對象,而後調用Ibinder對象裏自定義的通訊方法。this