我正在尝试制作后台服务,该服务即使在应用关闭时也会运行,它会获得当前位置,一旦此人接近目的地,应用就会启动。
package als.wakeup;
import com.google.android.gms.maps.model.LatLng;
import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class Awake_Alarm extends Service implements LocationListener{
Location location;
ConversePrefs cp;
ConversePrefs_sets cpss;
LatLng final_dest;
Settings sets;
double final_range;
LocationManager locationManager;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
final String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
cp = new ConversePrefs(this);
cpss = new ConversePrefs_sets(this);
sets = new Settings(this);
final_range = cp.GetIntSetting("Range", 250);
final_dest = cp.GetCoords();
if(cpss.GetIntSetting(sets.def_units_name, 0) == 1){
final_range = final_range * 1.09361;
}
Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING");
super.onCreate();
}
public double distanceGet(LatLng StartP, LatLng EndP) {
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6366000 * c;
}
@Override
public void onLocationChanged(Location arg0) {
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
double dest = distanceGet(me, final_dest);
if(dest <= final_range){
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING-"+String.valueOf(dest));
}
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away2-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING2-"+String.valueOf(dest));
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
它似乎工作正常,它启动等运行,当位置更改时,它会根据需要制作Toast文本,但是:到目标的距离不会更新,比如我启动应用,点击启动服务和距离到目的地是1500米,当位置变化时,它仍然会使吐司文字说:“1500米”
我做错了什么?