我正在开发一个应用程序,通过注册广播接收器android.provider.Telephony.SMS_RECEIVED来读取传入的短信。这是我的代码:
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
String message="";
String phoneNumber="";
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
message= message+ currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
//toast.show();
Intent speechIntent = new Intent();
speechIntent.setClass(context, Active.class);
speechIntent.putExtra("MESSAGE", message);
speechIntent.putExtra("NUMBER", phoneNumber);
// speechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startService(speechIntent);
} // end for loop
Intent speechIntent = new Intent();
speechIntent.setClass(context, Active.class);
speechIntent.putExtra("MESSAGE", message);
speechIntent.putExtra("NUMBER", phoneNumber);
// speechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startService(speechIntent);
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
我已经从服务初始化了texttospeech对象。这是代码:
public class Active extends Service implements TextToSpeech.OnInitListener,TextToSpeech.OnUtteranceCompletedListener{
private TextToSpeech tts = null;
private String msg = "";
String num="";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Intent startingIntent = this.getIntent();
if(intent!=null) {
msg = intent.getStringExtra("MESSAGE");
num = "Message from" + intent.getStringExtra("NUMBER");
tts = new TextToSpeech(this, this);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onInit(int status) {
try {
tts.speak( num, TextToSpeech.QUEUE_FLUSH, null);
tts.playSilence(1000,TextToSpeech.QUEUE_ADD,null);
tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
}catch(Exception e){}
}
@Override
public void onUtteranceCompleted(String utteranceId) {
// tts.shutdown();
// tts = null;
}
}
问题是它正在正确读取消息,它在服务类的msg变量中,但它没有执行代码: tts.speak(num,TextToSpeech.QUEUE_FLUSH,null); tts.playSilence(1000,TextToSpeech.QUEUE_ADD,NULL);
这两行没有被执行。请解释是否存在执行此操作的替代方法以及由于这些行未执行而导致执行这两行之后的类似代码行的原因。