我'在收到短信请求后编写应用程序以发送电话位置。接收短信的工作和发送短信也有效。如何在收到短信后发送短信?
MainActivity
final static String gpsLocationProvider = LocationManager.GPS_PROVIDER;
final static String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
static String loc;
public LocationManager locationManager;
static TextView messageBox;
public void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox = (TextView)findViewById(R.id.messageBox);
locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation_byGps =
locationManager.getLastKnownLocation(gpsLocationProvider);
Location lastKnownLocation_byNetwork =
locationManager.getLastKnownLocation(networkLocationProvider);
if (lastKnownLocation_byGps != null) {
loc = "gps " + lastKnownLocation_byGps.getLatitude();
}
if (lastKnownLocation_byNetwork != null) {
loc = "net lat:" + lastKnownLocation_byNetwork.getLatitude() + " long:" + lastKnownLocation_byNetwork.getLongitude();
}
}
public static void updateMessageBox(String msg) {
messageBox.setText(msg);
}
接收机
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
MainActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody());
}
}
收到sendSMS方法后在哪里发送短信?
答案 0 :(得分:1)
您可以在onReceive方法结束时调用发送短信代码语句,因为此方法在您收到短信时执行。