アクティビティを開始する必要がある 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()
およびonResume()
メソッドでは、Service
オブジェクトはおそらく null のままです。
こちらのチュートリアルをご覧ください: http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android
あなたがやろうとしているのは、アクティビティをサービスにバインドすることです。これにより、アクティビティに参照が与えられ、サービスで何でもできるようになります。(チュートリアルでは、アクティビティからのサービスの開始について説明していますが、もちろんこれを行う必要はありません)