您好我是Java的新手,我想知道当我已经转移到新活动时如何从另一个活动调用void方法。例如,我想打电话
来自onCreate(Bundle state)
PocketSphinxActivty.java
的
在我的新活动SMSReaderMain.java
我已经尝试了
PocketSphinxActivity ps = new PocketSphinxActivity();
ps.onCreate(null);
它没有错误,但是当SMSReaderMain.java
活动开始时它突然强制关闭而在实际设备中没有响应。
我也尝试更改为ps.onCreate(this)
或ps.onCreate(SMSReaderMain.this)
,但它会提供
PocketSphinxActivity类型中的方法setupRecognizer(File)不适用于参数 (SMSReaderMain)
这里是完整的代码,我想在我的新活动中调用几乎所有方法SMSReaderMain.java
PocketSphinxActivity.java
package edu.cmu.pocketsphinx.demo;
public class PocketSphinxActivity extends Activity implements
RecognitionListener {
//keyword yang digunakan dalem program untuk set ke even2 tertentu
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "drive mode";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "ok";
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Buat nyiapin User Interface
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
//captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
@Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
@Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
//nyocokin keyword dan pindah2 menu
@Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
try {
Intent i= null;
if (text.equals(KEYPHRASE)) {
switchSearch(MENU_SEARCH);
}
if (text.equals(DIGITS_SEARCH)) {
//panggil class SMSReaderMain
recognizer.stop();
i = new Intent(getApplicationContext(),SMSReaderMain.class);
startActivity(i);
}
if (text.equals(FORECAST_SEARCH)) {
switchSearch(FORECAST_SEARCH);
}
//else
//((TextView) findViewById(R.id.result_text)).setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
//nge pop up keyword yang sesuai kita ucapin sama library yg udah ada
@Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBeginningOfSpeech() {
}
//kembali ke menu utama
/*@Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}**/
//nampilin caption yg di mau sesuai dengan keyword
public void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
//inisiasi recognizer di awal
public void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/mulai.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
//File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
//recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
@Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
}
SMSReaderMAin.java
public class SMSReaderMain extends Activity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//PocketSphinxActivity ps = new PocketSphinxActivity();
//ps.setupRecognizer(null);
//ps.onPartialResult(null);
//ps.onResult(null);
//ps.switchSearch(null);
setContentView(R.layout.main_sms);
//recognizer.startListening(searchName);
toggle = (ToggleButton)findViewById(R.id.speechToggle);
smsText = (TextView)findViewById(R.id.sms_text);
smsSender = (TextView)findViewById(R.id.sms_sender);
toggleListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(isChecked){
speaker.allow(true);
speaker.speak(getString(R.string.start_speaking));
}else{
speaker.speak(getString(R.string.stop_speaking));
speaker.allow(false);
}
}
};
toggle.setOnCheckedChangeListener(toggleListener);
checkTTS();
initializeSMSReceiver();
registerSMSReceiver();
}
private void checkTTS(){
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(check, CHECK_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHECK_CODE){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
speaker = new Speaker(this);
}else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
private void registerSMSReceiver() {
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
private String getContactName(String phone){
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){
return cursor.getString(0);
}else {
return "unknown number";
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
speaker.destroy();
}
}
答案 0 :(得分:2)
对于Android中的编程方式,这是一种非常错误的方法。活动是由Android直接管理的Android应用程序中的主要核心组件之一,这意味着系统创建它们并由操作系统管理。 onCreate方法是生命周期的一部分,它由系统自动调用。 Here您拥有活动的生命周期。
开始新活动的方式是:
Intent intent = new Intent(mContext, MyActivity.class);
startActivity(intent);
由于活动是由系统实现的,因此您无法直接调用其上的方法。活动之间的通信方式是在intent中提供bundle对象,因此在新的Activity中,您可以从以下位置获取数据:
getIntent().getExtras()
您还可以使用startActivityForResult
代替startActivity
提供反向信息,并在onActivityResult
中收到结果。
您拥有所需的信息here。
答案 1 :(得分:1)
活动对应于您要在屏幕上显示的内容。如果您不打算显示任何内容,请不要创建活动。
在此示例中,您根本不需要PocketsphinxActivity
。您可以将PocketsphinxActivity
的所有方法移至SMSReaderMain
活动中。
如果您想将语音识别代码分成单独的类,则可以创建单独的PocketsphinxRecognizer
类,但是从Object
继承,而不是从Activity
继承。