#java #android #android-service
#java #Android #android-сервис
Вопрос:
Дело в том, что я пытаюсь использовать эмулятор, и это работает, но только после того, как я нажимаю «отправить местоположение на устройство» в эмуляторе, но до этого у меня нет возможности получить местоположение….Как мне получить местоположение при первом использовании этой службы?. У меня нет реального устройства, о котором я точно знаю, и эмулятор — мой единственный способ протестировать это на данный момент ….. Сначала я попытался отправить значение 0,0, чтобы посмотреть, вызовет ли это обновление местоположения, но это тоже не работает …… есть идеи?
@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")
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;
}
}
Комментарии:
1. в onCreate вы можете использовать
getLastKnownLocation(LocationManager.GPS_PROVIDER);
2. Я попробовал это с помощью отладчика, и он вылетает в строке, которую я вызываю getLastKnownLocation …..
@Override public void onCreate() { super.onCreate(); Location lastKnownLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
не могли бы вы предоставить фрагмент кода для того, что вы предлагаете?. Спасибо!
Ответ №1:
@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");
....
}
Комментарии:
1. Фактически, простое перемещение этой строки
Location lastKnownLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
сразу послеlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,listener);
отлично сработало…. Я размещал его в начале onCreate. Похоже, что getLastKnownLocation необходимо запустить после того, как метод requestLocationUpdates заработает. Большое вам спасибо, сэр!2. Я обновил свой пост окончательным кодом для дальнейшего использования. Большое вам спасибо!!