App的基本思想是:
1) BroadcastReceiver
、收到短信
2)当收到短信时,另一个活动被调用,发送另一个短信。
问题是,当BroadcastReceiver
调用其他活动(SMSMessaging)时,它的onCreate
方法被一次又一次地调用,因此 SMS 不断被一次又一次地发送。我的代码如下,请帮助我!
这是我的 BroadcastReciever 类:
package com.example.testing;
import java.util.Arrays;
import java.util.List;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
SmsMessage[] recievedMsgs = null;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
recievedMsgs = new SmsMessage[pdus.length];
for (int i = 0; i < recievedMsgs.length; i++) {
recievedMsgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " +
recievedMsgs[i].getOriginatingAddress() +
" :" +
recievedMsgs[i].getMessageBody().toString();
}
try {
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Intent i = new Intent(context,SMSMessaging.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Toast.makeText(context,"Yahoo",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
}
}
这是我的 SMSMessaging 类:
package com.example.testing;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SMSMessaging extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMSMessaging.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("03331234567", null, "auto sending ", pi, null);
finish();
}
}