在Service中执行onActivityResult功能

时间:2014-10-21 07:31:30

标签: android service

我正在使用此演讲文字。它在Activity中运行良好。

OnCreate中:

    // initialize imageButton
    btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

    // this method onclick called when speak button clicked
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // we create intent for speech recognization
            Intent intent = new Intent(
                    RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

            // here we set language for recognize
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

            try {
                // this line start google voice activity with data we set in
                // previous lines and set request code =RERESULT_SPEECH=1
                // you don't need to understand this in depth because these
                // are built in function for get voice from app
                startActivityForResult(intent, RESULT_SPEECH);


            } catch (ActivityNotFoundException a) {
                // if device give exception it means it not support speech
                // to text
                Toast t = Toast.makeText(getApplicationContext(),
                        "Ops! Your device doesn't support Speech to Text",
                        Toast.LENGTH_SHORT);
                t.show();// show toast message
            }
        }
    });

OnActivityResult:

// this method called when user stop speaking and then we get text of speech
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

    // request code 1 means speech activity
    case RESULT_SPEECH: {
        // if user speech any word and stop speak and data not null
        if (resultCode == RESULT_OK && null != data) {

            // voice data stored in arraylist as a text so we get this text
            // and set in textfield
            ArrayList<String> text = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

            // setText field with text which user speak
            Log.i("", text.get(0));
        }
        break;
    }

    }
}
}

但我想在服务中完成这项工作。在服务中,没有onActivityResult()。如何在服务中执行此操作?

1 个答案:

答案 0 :(得分:0)

据我所知,startActivityForResult无法Service

但是,您可以使用透明主题创建Activity。此Activity将启动Google SPEECH Activity,获取结果数据并转移到Service