我AIButton
在我的应用程序中使用,我有一个AsyncTask
在单击 AIButton 并接收一些命令后执行的操作,并且 AsyncTask 有时需要很长时间才能执行。
这是我的代码:
final AIConfiguration config = new AIConfiguration("xxx",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
listenButton = (AIButton) findViewById(R.id.micButton);
config.setRecognizerStartSound(getResources().openRawResourceFd(R.raw.test_start));
config.setRecognizerStopSound(getResources().openRawResourceFd(R.raw.test_stop));
config.setRecognizerCancelSound(getResources().openRawResourceFd(R.raw.test_cancel));
listenButton.initialize(config);
listenButton.setResultsListener(this);
这是AsnycTask
:
class translate extends AsyncTask<String, Void, String> {
String translatedText = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
loading.setMessage("Loading");
loading.show();
}
@Override
protected String doInBackground(String... params) {
String text = params[0];
String toBeConvertedIn = params[1];
Log.d("TEXT", text);
Log.d("TBCI", toBeConvertedIn);
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
HttpHandler httpHandler = new HttpHandler();
String url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=xxxxxxx&text=" + encodedText + "&lang=" + toBeConvertedIn;
String jsonStr = httpHandler.makeServiceCall(url);
if (jsonStr != null) {
Log.e(TAG, "Response from url: " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObj", String.valueOf(jsonObj));
JSONArray translatedTextObj = jsonObj.getJSONArray("text");
for (int i=0; i<translatedTextObj.length(); i++) {
translatedText = translatedTextObj.getString(i);
Log.d("translatedText", translatedText);
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
} else {
Log.e(TAG, "Couldn't get json from server.");
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, e.getMessage());
}
return translatedText;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
hTV.setText(s);
if (loading.isShowing()) {
loading.dismiss();
}
}
}
我在上面以这样AsyncTask
的onResult()
方法调用:
public void onResult(final AIResponse response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "onResult");
Log.i(TAG, "Received success response");
// this is example how to get different parts of result object
final Status status = response.getStatus();
Log.i(TAG, "Status code: " + status.getCode());
Log.i(TAG, "Status type: " + status.getErrorType());
final Result result = response.getResult();
Log.i(TAG, "Resolved query: " + result.getResolvedQuery());
Log.i(TAG, "Action: " + result.getAction());
final String speech = result.getFulfillment().getSpeech();
final Metadata metadata = result.getMetadata();
if (metadata != null) {
Log.i(TAG, "Intent id: " + metadata.getIntentId());
Log.i(TAG, "Intent name: " + metadata.getIntentName());
}
final HashMap<String, JsonElement> params = result.getParameters();
if (params != null && !params.isEmpty()) {
Log.i(TAG, "Parameters: ");
for (final Map.Entry<String, JsonElement> entry : params.entrySet()) {
switch (response.getResult().getMetadata().getIntentName()) {
case "Translate":
if (entry.getValue() != null) {
if (entry.getKey().equals("translate")) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.translate_alertdialog, null);
dialogBuilder.setView(dialogView);
final EditText textToTranslate = (EditText) dialogView.findViewById(R.id.text_to_translate);
final AutoCompleteTextView chooseLanguage = (AutoCompleteTextView) dialogView.findViewById(R.id.choose_language);
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, languages);
chooseLanguage.setAdapter(adapter);
dialogBuilder.setTitle("What should I translate?");
dialogBuilder.setPositiveButton("Translate", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (!textToTranslate.getText().toString().isEmpty()) {
if (!chooseLanguage.getText().toString().isEmpty()) {
switch (chooseLanguage.getText().toString().toLowerCase()) {
case "french":
new translate().execute(textToTranslate.getText().toString(), "az");
break;
}
}
}
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
} else {
Log.d("null", "No translate parameter");
}
} else {
Log.d("null", "No translate entry value");
}
break;
}
}
}
}
});
}
所以,我想要的是在单击 AIButton 时停止所有正在运行的 AsyncTask,以便停止以前的任务以执行新任务。这个怎么做?
这里的问题是你不能做这样的事情:listenButton.onClickListener()
在这里。