我正在开发一个 Android 应用程序,它有一个功能,当应用程序运行时,如果我收到一条新的 SMS 消息,则需要使用 TextToSpeech 读取该消息的内容。我知道如何使用 TextToSpeech 阅读文本。我在我的应用程序上写了两个类。一种是 MainActivity 扩展自 Activity,另一种是 SmsReceiver 扩展自 BroadcastReceiver。当 MainActivity 运行时收到短信时,我想使用 SmsReceiver 获取短信的内容并将其传递给 MainActivity,然后使用 TextToSpeech 在 MainActivity 中读取它。如何将短信内容从 SmsReceiver 传递到我的 MainActivity。我的 SmsReceiver 类的副本粘贴在下面。
public class SmsReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//this stops notifications to others
this.abortBroadcast();
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String from = null;
String msg= null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
from = msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
msg = msgs[i].getMessageBody().toString();
str += "\n";
}
System.out.println("from "+from);
System.out.println("msg "+msg);
Toast.makeText(context, "SMS Received : ",Toast.LENGTH_LONG).show();
//continue the normal process of sms and will get alert and reaches inbox
this.clearAbortBroadcast();
}
}
}