我正在开发一个
Android应用程序,它有一个功能,当应用程序运行时,如果我收到一条新的SMS消息,则需要使用TextToSpeech读取该消息的内容.我知道如何使用TextToSpeech阅读文本.我在我的应用程序上写了两个类.一个是MainActivity从Activity扩展而另一个是SmsReceiver从BroadcastReceiver扩展.当MainActivity运行时收到Sms我希望使用SmsReceiver获取sms消息的内容并将其传递给MainActivity,然后使用TextToSpeech在MainActivity中读取它.如何将sms的内容从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(); } }
}
解决方法
使用界面是一个适合我的解决方案.
在你的BroadcastReceiver中放入以下内容
public interface OnSmsReceivedListener { public void onSmsReceived(String sender,String message); }
然后添加监听器
private OnSmsReceivedListener listener = null;
public void setOnSmsReceivedListener(Context context) { this.listener = (OnSmsReceivedListener) context; }
然后在你的onReceive方法中,你可以做这样的事……
if (listener != null) { listener.onSmsReceived(sender,msg); }
在通过实现OnSmsReceivedListener接口创建并注册BroadcastReceiver的活动中,然后执行以下操作
public class SomeActivity extends Activity implements OnSmsReceivedListener..... private MissedCallActivity receiver;
receiver = new MissedCallActivity(); receiver.setOnSmsListener(this);
然后覆盖接口使用的方法.
@Override public void onSmsReceived(String sender,String message) { //Insert your text to speech code here }
这应该够了吧.
另外,不要忘记在onResume()方法中注册接收器,并在onPause()方法中注销它.另外,看看“from”如何以蓝色突出显示?这意味着它是Java语法的一部分,不能用作变量.