android 调用服务,android-从服务类调用活动类方法

定义您的服务将用于传达事件的接口:

public interface ServiceCallbacks {

void doSomething();

}

编写您的服务类。 您的活动将绑定到该服务,因此请遵循此处显示的示例。 另外,我们将添加一个方法来设置setCallbacks。

public class MyService extends Service {

// Binder given to clients

private final IBinder binder = new LocalBinder();

// Registered callbacks

private ServiceCallbacks serviceCallbacks;

// Class used for the client Binder.

public class LocalBinder extends Binder {

MyService getService() {

// Return this instance of MyService so clients can call public methods

return MyService.this;

}

}

@Override

public IBinder onBind(Intent intent) {

return binder;

}

public void setCallbacks(ServiceCallbacks callbacks) {

serviceCallbacks = callbacks;

}

}

按照相同的指南编写您的Activity类,但也要使其实现ServiceCallbacks接口。 与服务绑定/解除绑定时,将通过在服务上调用setCallbacks进行注册/注销。

public class MyActivity extends Activity implements ServiceCallbacks {

private MyService myService;

private boolean bound = false;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(...);

}

@Override

protected void onStart() {

super.onStart();

// bind to Service

Intent intent = new Intent(this, MyService.class);

bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

}

@Override

protected void onStop() {

super.onStop();

// Unbind from service

if (bound) {

myService.setCallbacks(null); // unregister

unbindService(serviceConnection);

bound = false;

}

}

/** Callbacks for service binding, passed to bindService() */

private ServiceConnection serviceConnection = new ServiceConnection() {

@Override

public void onServiceConnected(ComponentName className, IBinder service) {

// cast the IBinder and get MyService instance

LocalBinder binder = (LocalBinder) service;

myService = binder.getService();

bound = true;

myService.setCallbacks(MyActivity.this); // register

}

@Override

public void onServiceDisconnected(ComponentName arg0) {

bound = false;

}

};

/* Defined by ServiceCallbacks interface */

@Override

public void doSomething() {

...

}

}

现在,当您的服务想要与活动进行通信时,只需调用前面的接口方法之一即可。 服务内幕:

if (serviceCallbacks != null) {

serviceCallbacks.doSomething();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值