我班上的onReceive()会收听短信并发送短信回复,一切正常但只有一次。发送短信后,应用程序关闭并显示消息"不幸的是,您的应用已停止"。我希望它保持活跃。我想知道我错过了什么地方。谢谢你的帮助!
public class SMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
private static final String TAG="SMSReceiver";
@Override
public void onReceive(Context context,Intent intent){
SmsManager smsManager=SmsManager.getDefault();
int i;
Toast.makeText(context,"Intent recieved",Toast.LENGTH_LONG).show();
Log.i(TAG,"Intent recieved: "+intent.getAction());
String messageContent="";
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
messageContent=messages[i].getMessageBody().toString();
}
if (messages.length > -1 && messageContent.charAt(8)=='#') {
Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
Toast.makeText(context, "Message received from victim: "+messageContent, Toast.LENGTH_LONG).show();
smsManager.sendTextMessage("+919032687185",null,"Request#",null,null);
//Toast.makeText(context, "SMS sent.",Toast.LENGTH_LONG).show();
/*for(i=0;i<7;i++){
MediaPlayer mediaPlayer=MediaPlayer.create(context, R.raw.fire_engine_siren_could_be_police_ambulance_etc);
mediaPlayer.start();
}*/
}
/*else if(messages.length > -1 && messageContent.charAt(6) == '#'){
Log.i(TAG, "Location from patrol" + messages[0].getMessageBody());
Toast.makeText(context, "Message received from ambulance: "+messageContent, Toast.LENGTH_LONG).show();
}*/
}
}
}
}
答案 0 :(得分:0)
好像你得到的是java.lang.StringIndexOutOfBoundsException
,我的猜测是罪魁祸首messageContent.charAt(8)
,因为logcat表示length=8; index=8
如果需要找到此位置,请尝试使用indexOf。它更灵活,不会向你抛出异常。