Java 第一次执行服务时,如何获取最后一个已知位置?
问题是,我正在模拟器上尝试,它可以工作,但只有在我按下模拟器上的“发送位置到设备”之后,我才有机会获取位置……我如何第一次使用此服务获取位置?。我现在还没有真正的设备,模拟器是我目前唯一的测试方法……我一开始试着发送一个0,0,看看这是否会触发位置更新,但它不起作用……有什么想法吗Java 第一次执行服务时,如何获取最后一个已知位置?,java,android,android-service,Java,Android,Android Service,问题是,我正在模拟器上尝试,它可以工作,但只有在我按下模拟器上的“发送位置到设备”之后,我才有机会获取位置……我如何第一次使用此服务获取位置?。我现在还没有真正的设备,模拟器是我目前唯一的测试方法……我一开始试着发送一个0,0,看看这是否会触发位置更新,但它不起作用……有什么想法吗 @SuppressWarnings("MissingPermission") public class GPSService extends Service { private LocationListen
@SuppressWarnings("MissingPermission")
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private String lastKnownLatitude;
private String lastKnownLongitude;
private Boolean isFirstTime=true;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
broadcastLocation("0","0");
listener= new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
Intent intentSendLocationMainActivity = new Intent("location_update");
lastKnownLatitude=""+location.getLatitude();
lastKnownLongitude=""+location.getLongitude();
Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
broadcastLocation(lastKnownLatitude,lastKnownLongitude);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("GPS-Stat-Changed",s);
}
@Override
public void onProviderEnabled(String s) {
Log.d("GPS-Provider-Enabled",s);
}
@Override
public void onProviderDisabled(String s) {
Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activateGPSIntent);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission, listen for updates every 3 seconds
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
//unregistering the listener
/*if(locationManager != null){
locationManager.removeUpdates(listener);
}*/
}
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//here you can call a background network request to post you location to server when app is killed
Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
//stopSelf(); //call this method to stop the service
}
public void broadcastLocation(String latitude,String longitude){
Intent intentSendLocationMainActivity = new Intent("location_update");
intentSendLocationMainActivity.putExtra("latitude",latitude);
intentSendLocationMainActivity.putExtra("longitude",longitude);
//I need to differentiate here if the app is killed or not to send the location to main activity or to a server
sendBroadcast(intentSendLocationMainActivity);
}
}
编辑:这是完整的服务工作。这是它第一次使用getLastKnownLocation()获取坐标,并使用侦听器onLocationChanged()成功获取坐标
@SuppressWarnings(“MissingPermission”)
公共类GPSService扩展服务{
私密地点监听;
私人场所经理场所经理;
私有字符串lastnownlatitude;
私有字符串lastnownlongude;
私有布尔值isFirstTime=true;
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
listener=新位置listener(){
@凌驾
已更改位置上的公共无效(位置){
//为了将数据传输到主活动,我在主活动中使用广播接收器,并使用意图过滤器位置更新
意向意向转让意向活动=新意向(“位置更新”);
lastKnownLatitude=”“+位置。getLatitude();
lastKnownLongitude=”“+位置。getLongitude();
Log.d(“位置更新”,lastKnownLatitude+“长:”+lastKnownLatitude);
广播位置(lastKnownLatitude、LastKnownLongude);
}
@凌驾
状态已更改的公共void(字符串s、int i、Bundle){
Log.d(“GPS状态改变”,s);
}
@凌驾
已提供已启用的公共void(字符串s){
Log.d(“GPS提供程序已启用”,s);
}
@凌驾
公共无效onProviderDisabled(字符串s){
Intent activateGPSIntent=新意图(设置、操作位置、源设置);
activateGPSIntent.setFlags(Intent.FLAG\u ACTIVITY\u NEW\u TASK);
起始触觉(激活EGPSINTENT);
}
};
locationManager=(locationManager)getApplicationContext().getSystemService(Context.LOCATION\u服务);
//noinspection Missing权限,每3秒侦听一次更新
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序,5000,0,侦听器);
地图坐标=getLastKnownLocation(locationManager);
广播位置(坐标.get(“纬度”)、坐标.get(“经度”);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.d(“ClearFromRecentService”,“服务已启动”);
Log.d(“最后一次和最后一次”,lastKnownLatitude+“”+lastKnownLatitude);
返回开始时间;
}
@凌驾
公共空间{
super.ondestory();
Log.d(“ClearFromRecentService”,“服务已销毁,删除更新位置侦听器”);
//注销侦听器
/*如果(locationManager!=null){
locationManager.RemoveUpdate(侦听器);
}*/
}
公共void onTaskRemoved(Intent rootIntent){
Log.e(“ClearFromRecentService”、“END”);
//在这里,当应用程序被终止时,您可以调用后台网络请求将您的位置发布到服务器
Toast.makeText(getApplicationContext(),“我仍在获取用户坐标”,Toast.LENGTH\u LONG.show();
//stopSelf();//调用此方法停止服务
}
私有位置(字符串纬度、字符串经度){
意向意向转让意向活动=新意向(“位置更新”);
intentSendLocationMainActivity.putExtra(“纬度”,纬度);
intentSendLocationMainActivity.putExtra(“经度”,经度);
//我需要在这里区分应用程序是否被终止,是否将位置发送到主活动或服务器
发送广播(IntentSendLocationMain活动);
}
私有地图getLastKnownLocation(LocationManager lm){
Location lastKnownLocation=lm.getLastKnownLocation(LocationManager.GPS\U提供程序);
字符串ll=”“+lastKnownLocation.getLatitude();
地图坐标=新的HashMap();
//每次检查此值时,它可能为空
if(lastKnownLocation!=null){
坐标.put(“纬度”,“lastKnownLocation.getLatitude());
坐标.put(“经度”,“lastKnownLocation.getLongitude());
}否则{
坐标。放置(“纬度”,“0”);
坐标。放置(“经度”,“0”);
}
返回坐标;
}
}
在onCreate中,您可以使用getLastKnownLocation(LocationManager.GPS\U PROVIDER)代码>我用调试器尝试了这一点,它在我调用getLastKnownLocation…..的线路上崩溃了<代码>@Override public void onCreate(){super.onCreate();Location lastnownlocation=locationManager.getlastnownlocation(locationManager.GPS_提供程序)
你能提供一个关于你建议的代码片段吗?。谢谢!事实上,只要移动这一行Location-lastnownlocation=locationManager.getlastnownlocation(locationManager.GPS\u PROVIDER);
就在locationManager.requestLocationUpdates(locationManager.GPS\u PROVIDER,5000,0,listener)之后
工作得很好…我把它放在了onCreate的边缘。它看起来像getLastKnownLocation需要在requestLocationUpdates方法之后运行。非常感谢先生!我用最后的代码更新了我的帖子,以供将来参考。非常感谢!!
@SuppressWarnings("MissingPermission")
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private String lastKnownLatitude;
private String lastKnownLongitude;
private Boolean isFirstTime=true;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
listener= new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
Intent intentSendLocationMainActivity = new Intent("location_update");
lastKnownLatitude=""+location.getLatitude();
lastKnownLongitude=""+location.getLongitude();
Log.d("LOCATION-UPDATE",lastKnownLatitude+" long:"+lastKnownLongitude);
broadcastLocation(lastKnownLatitude,lastKnownLongitude);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("GPS-Stat-Changed",s);
}
@Override
public void onProviderEnabled(String s) {
Log.d("GPS-Provider-Enabled",s);
}
@Override
public void onProviderDisabled(String s) {
Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activateGPSIntent);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission, listen for updates every 3 seconds
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
Map<String, String> coordinates=getLastKnownLocation(locationManager);
broadcastLocation(coordinates.get("latitude"),coordinates.get("longitude"));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
Log.d("LAST_LAT_AND_LONG",lastKnownLatitude+" "+lastKnownLongitude);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
//unregistering the listener
/*if(locationManager != null){
locationManager.removeUpdates(listener);
}*/
}
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//here you can call a background network request to post you location to server when app is killed
Toast.makeText(getApplicationContext(), "I'm still getting user coordinates", Toast.LENGTH_LONG).show();
//stopSelf(); //call this method to stop the service
}
private void broadcastLocation(String latitude,String longitude){
Intent intentSendLocationMainActivity = new Intent("location_update");
intentSendLocationMainActivity.putExtra("latitude",latitude);
intentSendLocationMainActivity.putExtra("longitude",longitude);
//I need to differentiate here if the app is killed or not to send the location to main activity or to a server
sendBroadcast(intentSendLocationMainActivity);
}
private Map<String, String> getLastKnownLocation(LocationManager lm){
Location lastKnownLocation=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String ll=""+lastKnownLocation.getLatitude();
Map<String, String> coordinates = new HashMap<String, String>();
// Check everytime this value, it may be null
if(lastKnownLocation != null){
coordinates.put("latitude",""+lastKnownLocation.getLatitude());
coordinates.put("longitude",""+lastKnownLocation.getLongitude());
}else{
coordinates.put("latitude","0");
coordinates.put("longitude","0");
}
return coordinates;
}
}
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Check everytime this value, it may be null
if(lastKnownLocation != null){
double latitude = lastKnownLocation.getLatitude();
double longitude = lastKnownLocation.getLongitude();
// Use values as you wish
}
broadcastLocation("0","0");
....
}