原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://930307.blog.51cto.com/7950022/1349429
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
|
package
cn.cbd.service;
import
android.app.Service;
import
android.content.Intent;
import
android.os.Binder;
import
android.os.IBinder;
public
class
MyService
extends
Service
{
@Override
public
void
onCreate()
{
super
.onCreate();
}
@Override
public
IBinder onBind(Intent intent)
{
return
new
MyBinder();
}
@Override
public
void
onDestroy()
{
super
.onDestroy();
}
public
class
MyBinder
extends
Binder
{
public
String getname()
{
return
getName();
}
}
/**
* 在服务中自定义一个方法,我们要在activity中调用这个方法
*
* @return
*/
public
String getName()
{
return
"张三"
;
}
}
|
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
|
package
cn.cbd.service;
import
android.app.Activity;
import
android.content.ComponentName;
import
android.content.Context;
import
android.content.Intent;
import
android.content.ServiceConnection;
import
android.os.Bundle;
import
android.os.IBinder;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.TextView;
public
class
ServiceTestActivity
extends
Activity
{
private
Button btn_bindService;
private
TextView tv_show;
private
MyServiceConnection conn;
private
MyService.MyBinder myBinder;
public
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_bindService = (Button) findViewById(R.id.btn_bindService);
tv_show = (TextView) findViewById(R.id.tv_show);
btn_bindService.setOnClickListener(
new
OnClickListener()
{
public
void
onClick(View v)
{
// 开启服务
Intent service =
new
Intent(ServiceTestActivity.
this
,
MyService.
class
);
conn =
new
MyServiceConnection();
// startService(service)只能单纯的开启一个服务,要想调用服务服务中的方法,必须用bindService和unbindService
// startService(service);
bindService(service, conn, Context.BIND_AUTO_CREATE);
}
});
}
/**
* 自定义一个类,实现ServiceConnection接口,并重写其两个方法
* @author Administrator
*
*/
public
class
MyServiceConnection
implements
ServiceConnection
{
//当绑定服务成功的时候会调用此方法
public
void
onServiceConnected(ComponentName name, IBinder service)
{
//得到MyService.MyBinder对象,我们通过这个对象来操作服务中的方法
myBinder = (MyService.MyBinder) service;
//调用服务中的getname()方法并把值设置到TextView上进行显示
tv_show.setText(myBinder.getname());
}
public
void
onServiceDisconnected(ComponentName name)
{
}
}
@Override
protected
void
onDestroy()
{
// 在程序销毁的时候要对服务解除绑定
unbindService(conn);
super
.onDestroy();
}
}
|