我正在尝试创建一个可以收听各种命令并相应地响应它的Android应用程序。例如,如果我按下麦克风并说"打开whatsapp"它就会这样做。 问题是如何使用有限编码打开各种应用程序?
以下代码是打开whatsapp,但如果我必须打开其他各种应用程序,我是否需要为各种应用程序编写相同的IF语句?它不会太长吗? 请提供更好的解决方案。
package example.bot;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends Activity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 1234;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
* */
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (result.size() == 0) {
} else {
String mostLikelyThingHeard = result.get(0);
// toUpperCase() used to make string comparison equal
if (mostLikelyThingHeard.toUpperCase().equals("OPEN WHATSAPP")) {
//informationMenu();
txtSpeechInput.setText(result.get(0));
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
//if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} //else if()
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
//private void informationMenu() {
// Intent intent = new Intent(this, open_app.class);
// startActivity(intent);
//}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}