我有一个需要启动活动的WallpaperEngine - 一个简单的选项菜单。Android从活动到服务/引擎进行通信的最佳方式
我需要该菜单选择的结果。从活动返回到服务的最佳方式是什么,因为它没有提及服务,我不能做startActivityForResult。
谢谢!
我有一个需要启动活动的WallpaperEngine - 一个简单的选项菜单。Android从活动到服务/引擎进行通信的最佳方式
我需要该菜单选择的结果。从活动返回到服务的最佳方式是什么,因为它没有提及服务,我不能做startActivityForResult。
谢谢!
看看这里的教程: http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android
你会做什么你的活动结合,这将给活性的参考和做任何事情与服务能力的服务。 (本教程包括从活动启动该服务,但你并不需要做的,当然这一点)
您可以使用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
。请注意,绑定是异步的。当您可以与Activity
的UI交互时,连接已建立,但在onCreate()
和onResume()
方法中,您的Service
对象可能仍为空。
谢谢,这是很好的学习这种方法。然而onBind不能在壁纸服务中重写 - 它的最终方法:(也许我会尝试本地广播。 – serenskye
如果服务和活动在同一个应用程序(和进程)中,您可以使用http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html从compat包 – sherpya
这工作对我来说很好,我会将其标记为已接受的答案... – serenskye