我见过很多关于这个问题的帖子,但我找不到任何解决方案。
我的问题是我想通过使用Asynctask在后台运行Google语音识别器,但我不能在AsyncTask子类中使用setActivityForResult()
。任何人都可以帮我解决这个问题吗?
如果有任何其他方法可以实现我的目标,那么请提出建议。 提前谢谢!
以下是我更好地理解问题的代码: - 我的主要活动: -
package com.mrg.simonsays;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
BackgroundRecognise.execute();
}
}
我不知道为execute()方法提供什么参数 BackgroundRecognise活动: -
package com.mrg.simonsays;
import android.content.Intent;
import android.os.AsyncTask;
import android.speech.RecognizerIntent;
public class BackgroundRecognise extends AsyncTask<Void, Void, Void>{
String str = "";
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Give Your Command");
BackgroundRecognise.this.startActivityForResult(i, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub if
if (resultCode == RESULT_OK) {
List<ApplicationInfo> packages;
PackageManager pm = getPackageManager();
packages = pm.getInstalledApplications(0);
ArrayList<String> results = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for (ApplicationInfo packageInfo : packages) {
str = pm.getApplicationLabel(packageInfo).toString();
for (String i : results) {
if (str.equalsIgnoreCase(i)) {
Intent LaunchIntent = pm
.getLaunchIntentForPackage(packageInfo.packageName);
startActivity(LaunchIntent);
}
}
}
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
我基本上要做的是:我想在后台使用AsyncTask运行Google语音识别器。但我不能在其任何方法中使用startActivityForResult()。谁能帮助我怎么做?
答案 0 :(得分:0)
将startActivityForResult
用法放在:
@Override
protected void onPostExecute(String result) {
//put here
}
注意:onPostExecute
是Async类的一部分。