我有一个需要启动活动的 WallpaperEngine - 一个简单的选项菜单。
我需要该菜单选择的结果。从活动返回服务的最佳方式是什么,因为它没有对服务的引用,而且我不能执行 startActivityForResult。
谢谢!
我有一个需要启动活动的 WallpaperEngine - 一个简单的选项菜单。
我需要该菜单选择的结果。从活动返回服务的最佳方式是什么,因为它没有对服务的引用,而且我不能执行 startActivityForResult。
谢谢!
您可以使用Binders
和ServiceConnection
连接Serivce
到您的Activity
.
在你的Activity
:
private YourService mService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ((YourBinder)service).getService();
}
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
@Override
protected void onResume() {
bindService(new Intent(this, YourService.class), mConnection, Context.BIND_AUTO_CREATE);
super.onResume();
}
@Override
protected void onPause() {
if(mConnection != null){
unbindService(mConnection);
}
super.onPause();
}
你的Binder
:
public class YourBinder extends Binder {
private WeakReference<YourService> mService;
public YourBinder(YourService service){
mService = new WeakReference<YourService>(service)
}
public YourService getService(){
return mService.get();
}
}
在你的Service
:
@Override
public IBinder onBind(Intent intent) {
return new YourBinder(this);
}
在此之后,您可以Service
从您的Activity
. 请注意,绑定是异步的。当您可以与 UI 交互时Activity
,连接已经建立,但在onCreate()
andonResume()
方法中,您的Service
对象可能仍为 null。
看看这里的教程: http ://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android
您将要做的是将您的活动绑定到服务,这将为活动提供参考以及对服务执行任何操作的能力。(本教程涵盖从活动启动服务,但您当然不需要这样做)