2

アクティビティを開始する必要がある WallpaperEngine があります。単純なオプション メニューです。

そのメニュー選択の結果が必要です。サービスへの参照がなく、startActivityForResult を実行できないため、アクティビティからサービスに通信するための最良の方法は何ですか。

ありがとう!

4

2 に答える 2

2

とを使用してBindersServiceConnectionを に接続でき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 のままです。

于 2012-08-24T09:08:50.473 に答える
0

こちらのチュートリアルをご覧ください: http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android

あなたがやろうとしているのは、アクティビティをサービスにバインドすることです。これにより、アクティビティに参照が与えられ、サービスで何でもできるようになります。(チュートリアルでは、アクティビティからのサービスの開始について説明していますが、もちろんこれを行う必要はありません)

于 2012-08-24T09:03:05.967 に答える