1.startService()
2.onbind()
一,开启服务
activity里:
Intent intent = new Intent(this, UploadLocationService.class); startService(intent);
服务类:
public class UploadLocationService extends Service {
@Override
public IBinder onBind(Intent intent) {
Logger.d("测试。执行onbind");
Toast.show("执行onbind");
return null;
}
@Override
public void onCreate() {
Logger.d("测试。执行onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.d("测试。执行onStartCommand");
// return super.onStartCommand(intent, flags, startId);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Logger.d("测试。执行onDestroy");
stopForeground(true);
super.onDestroy();
}
}
二,绑定开启服务(同时可以调用service里面的方法)
activity:(startservice()开启)
private Intent intent;
private LocationServiceConn myServiceConn;
private InterfaceMyBinder myBinder;
public void startservice() {
Logger.d("测试。调用:startservice");
intent = new Intent(this, UploadLocationServiceTest.class);
myServiceConn = new LocationServiceConn();
//绑定服务(intent对象,绑定服务的监听器,一般为BIND_AUTO_CREATE常量)
bindService(intent, myServiceConn, BIND_AUTO_CREATE);
}
private class LocationServiceConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
//iBinder为服务里面onBind()方法返回的对象,所以可以强转为自定义InterfaceMyBinder类型
myBinder = (InterfaceMyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
//调用服务里面的方法
public void getServiceMethod() {
Logger.d("测试。调用:getServiceMethod");
myBinder.protectMethodInMyService();
}
//接口,让service里面的binder实现
public interface InterfaceMyBinder {
void protectMethodInMyService();
}
服务类:
public class UploadLocationServiceTest extends Service {
@Override
public IBinder onBind(Intent intent) {
Logger.d("测试。执行onbind");
Toast.show("执行onbind");
return new MyBinder();
}
@Override
public void onCreate() {
Logger.d("测试。执行onCreate");
super.onCreate();
}
private class MyBinder extends Binder implements HomeActivity.InterfaceMyBinder {
@Override
public void protectMethodInMyService() {
MyServicemethod();
}
}
/**
* 可被绑定者调用的服务里的方法
*/
private void MyServicemethod() {
Logger.d("测试。调用:服务里面的方法");
}
}
本文详细解析了在Android中如何使用startService()方法启动服务,以及如何通过bindService()方法绑定并调用服务内部的方法。包括Intent的使用,Service生命周期方法的执行流程,以及自定义Binder接口实现跨组件通信的具体步骤。
5252

被折叠的 条评论
为什么被折叠?



