15

簡単な質問がありますが、このアクティビティが同じサービスから開始された場合 (インテントを使用)、サービスでメソッド onActivityResult() を処理することは可能ですか?

私の場合、 SpeechRegnition を開始し、 Speak を開始し、サービスで結果を取得し、すべてをバックグラウンドで開始したい (メインサービスはウィジェットから開始) 、

ありがとう 。

4

3 に答える 3

11

それが誰であれ、最近の反対票をありがとう。2012 年に私が返した以前の回答はまったくナンセンスなので、適切な回答を書くことにしました。

Activity の結果を Service で処理することはできませんが、onActivityResult() から取得したデータを Service に渡すことはできます。

サービスがすでに実行されている場合は、次のように、イベントを処理する新しいインテントで startService() を呼び出すことができます

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CODE && resultCode == RESULT_OK) {
        notifyService(data);
    }
}

private void notifyService(final Intent data) {
    final Intent intent = new Intent(this, MyService.class);
    intent.setAction(MyService.ACTION_HANDLE_DATA);
    intent.putExtra(MyService.EXTRA_DATA, data);
    startService(intent);
}

また、Service でアクションを処理します。すでに実行されている場合は再起動されません。それ以外の場合は開始されます

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        final String action = intent.getAction();
        if (action != null) {
            switch (action) {
                case ACTION_HANDLE_DATA:
                    handleData(intent.getParcelableExtra(EXTRA_DATA));
                    // Implement your handleData method. Remember not to confuse Intents, or even better make your own Parcelable
                    break;
            }
        }
    }
    return START_NOT_STICKY;
}
于 2012-11-28T15:16:46.080 に答える