我的应用程序有一个按钮,onClick将消息发送到特定号码并侦听传入消息。我有两个与此相关的问题:
发件人的电话号码存储在共享偏好中。
这是我发送短信的活动。
public void onClick(View arg0) {
SmsManager smsmanager=SmsManager.getDefault();
String myMessage="2.65";
smsmanager.sendTextMessage(sendTo, null, myMessage, null, null);
Toast.makeText(this,"sms sent",Toast.LENGTH_LONG).show();
final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter filter = new IntentFilter(SMS_RECEIVED);
BroadcastReceiver receiver = new SmsReceiver();
registerReceiver(receiver,filter);
}
这是我的SmsReceiver类,它扩展了广播接收器,对传入的消息进行了标记,并通过意图将令牌传递给下一个活动。我在最后添加了toast消息进行验证。在接收和开始下一个活动时,Toast显示两次。换句话说,我的活动开始了两次!!
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = 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]);
System.out.println(msgs[i].toString());
str += "SMS from " + msgs[i].getOriginatingAddress();
ph += msgs[i].getMessageBody().toString();
}
}
StringTokenizer st = new StringTokenizer(ph, ".");
i=0;
while(st.hasMoreTokens())
{
arr[i] = st.nextToken();
i++;
}
Toast.makeText(context,ph,Toast.LENGTH_LONG).show();
Toast.makeText(context,arr[0],Toast.LENGTH_LONG).show();
Toast.makeText(context,arr[1],Toast.LENGTH_LONG).show();
Intent l = new Intent(context,Stats.class);
l.putExtra("dig1", arr[0]);
l.putExtra("dig2", arr[1]);
l.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
l.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(l);
}
Android Manifest文件如下
<activity android:name=".xyz" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity android:name=".Stats">
</activity>