[英]How can I create a TextToSpeech object in an Activity called from the broadcast receiver?
我是android的新手,我正在嘗試創建一個呼叫者姓名播音員應用程序。 以下是我的代碼。 日志顯示代碼執行得很好,即TextToSpeech構造函數正在執行並到達onInit方法直到最后,但是,當我對其進行測試時,聽不到聲音。
這是我的CustomBroadcastReceiver.java:
public class CustomBroadcastReceiver extends BroadcastReceiver {
protected String newSender;
@Override
public void onReceive(Context context, Intent intent) {
Log.v("", "logger WE ARE INSIDE!!!!!!!!!!!");
Intent i=new Intent(context,ReceiverActivity.class);
TelephonyManager telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener,
PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr = bundle.getString("incoming_number");
Log.v("", "logger phoneNr: " + phoneNr);
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNr));
Cursor cursor = context.getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME }, phoneNr, null, null);
if (cursor.moveToFirst()) {
newSender = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
i.putExtra("ID", newSender);
Log.d("","logger intent" + i.getStringExtra("ID"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
cursor.close();
}
}
這是ReceiverActivity.java
public class ReceiverActivity extends Activity implements TextToSpeech.OnInitListener{
String name;
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Log.d("","logger reached ReceiverActivity");
tts = new TextToSpeech(this, this);
Log.d("","logger created tts object");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.receiver, menu);
return true;
}
@Override
public void onInit(int status) {
Log.d("","logger reached onInit");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US); // java.Util.Locale for
// country codes
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
tts.speak(name, TextToSpeech.QUEUE_FLUSH, null);
Log.d("","logger speak executed");
}
}
你能告訴我我要去哪里錯嗎?
首先,在您的活動類中初始化Text-To-Speech對象,然后使用string參數創建靜態方法,該參數包含Text-To-Speech的語音方法。
並使用您要聲明的字符串從您的broadcastreceiver調用此靜態方法。
public static void speakOut(String message) {
System.out.println("Message is: " + message);
tts.speak(message, TextToSpeech.QUEUE_ADD, null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.