我有一个简单的应用程序,只需单击一个按钮即可获取 gps 坐标。
这是代码:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Coordinates extends Activity {
protected LocationManager locationManager;
protected Button retrieveLocationButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(Coordinates.this, message,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
}
我还制作了接收短信的 SmsReceiver 类:
这是代码:
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 SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
if (msgs.length >= 0) {
msgs[0] = SmsMessage.createFromPdu((byte[]) pdus[0]);
String message = msgs[0].getMessageBody().toString();
if (message.toString().matches("GPS")){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();}
else
{Toast.makeText(context,"Nothing",100 ).show();
}
}
}
}
}
一切正常,但我的问题是,如何触发 gps 以特定SMS而不是按钮显示坐标。
提前致谢!