我正在看其他帖子,但我的不能。当我距离目标位置“x”米时,我想更新我的位置并发出警报声。
我用过这段代码:
private TextView m1TextMessage, m2TextMessage, m3TextMessage;
private LocationManager locationManager;
private Location targetLocation;
double longitude, latitude;
private float distancia;
ProgressDialog pd;
LocationListener listener;
这是我的位置监听器:
public class MyLocationListener implements LocationListener {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float dist=0;
float error=0;
//Escribir posición actual en m1TextMessage
latitude =location.getLatitude();
longitude = location.getLongitude();
//calcular distancia al destino y error estimado
//Escribir distancia al destino y error en m3TextMessage
Location loc2= new Location(LocationManager.GPS_PROVIDER);
if (loc2 != null)
{
dist=location.distanceTo(targetLocation);
error = location.getAccuracy();
if(dist < distancia){
Toast.makeText(getApplicationContext(), "Distancia menor a 10 metros, "+dist+" metros.",Toast.LENGTH_SHORT).show();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
}else
Toast.makeText(getApplicationContext(), "location actual es null!!",Toast.LENGTH_SHORT).show();
m1TextMessage.setText("Posición actual: "+longitude+", "+latitude+"\n");
m2TextMessage.setText("Posición objetivo: "+targetLocation.getLatitude()+", "+targetLocation.getLongitude()+"\n");
m3TextMessage.setText("Distancia al objetivo: "+dist+"\nError estimado: "+error);
//Lanzar un Toast si la distancia al destino es inferior a 10 metros
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m1TextMessage=(TextView) findViewById(R.id.actualPos);
m2TextMessage=(TextView) findViewById(R.id.destino);
m3TextMessage=(TextView) findViewById(R.id.distanciaa);
Button localiza = (Button)findViewById(R.id.button1);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
localiza.setOnClickListener(this);
}
public class GPSLocation extends AsyncTask<Void, Void, Void>
{
boolean running =true;
@Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(PracticaGPS.this);
pd.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
pd.cancel();
}
});
longitude=0;
latitude =0;
getLonLat();
pd.setCancelable(true);
pd.setMessage("Getting GPS Location...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
@Override
protected void onPostExecute(Void result)
{
pd.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
boolean isDataSubmitted = false;
while(!isDataSubmitted)
{
if(longitude !=0 && latitude!=0)
{
isDataSubmitted = true;
Log.d("LONGITUD", ""+longitude);
Log.d("LATITUDE", ""+latitude);
}
}
return null;
}
}
public void getLonLat(){
listener = new MyLocationListener();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
(locationManager).requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,listener);
new GPSLocation().execute();
}else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, listener);
Log.d("Long", ""+longitude);
} else
enableLocationSettings();
}
@Override
public void onStart(){
//Crear servicio de localización LocationManager
//Determinar si el GPS está encendido
//Caso esté apagado, permitir al usuario activarlo mediante método enableLocationSettings()
//Solicitar actualizaciones de posición al proveedor de GPS (opcionalmente también al proveedor de red)
//Nota: el LocationListener ya ha sido creado: listener
super.onStart();
}
private void enableLocationSettings() { //enable Location services is necessary
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
@Override
public void onStop(){
locationManager.removeUpdates(listener);
super.onStop();
}
public void onClick(View v) {
EditText lat, lon, distan;
lat = (EditText)findViewById(R.id.latitud);
lon = (EditText)findViewById(R.id.longitud);
targetLocation = new Location("Target Position");
targetLocation.setLatitude(Double.valueOf(lat.getText().toString())); //punto pre-definido,
targetLocation.setLongitude(Double.valueOf(lon.getText().toString())); //no cambiar el valor
targetLocation.setAltitude(0);
distan = (EditText)findViewById(R.id.distancia);
distancia = Float.valueOf(distan.getText().toString());
new GPSLocation().execute();
}
}
这是我的 xml 代码:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitud: " />
<EditText
android:id="@+id/longitud"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:ems="10" />
<TextView
android:id="@+id/texto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitud: " />
<EditText
android:id="@+id/latitud"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distancia mínima alarma" />
<EditText
android:id="@+id/distancia"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enviar Localizacion" />
<TextView
android:id="@+id/actualPos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/destino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/distanciaa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
我想这很简单,但我可以管理它。谢谢你。