Android:收到一条后发送短信

Android: send sms after receiving one

我正在编写一个应用程序以在收到短信请求后发送 phone 位置信息。接收短信的作品和发送短信的作品也。收到短信怎么办?

主要活动

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方法放在哪里?

你可以在onReceive方法的最后调用你的发送短信代码语句,因为这个方法是在你收到短信时执行的。