私のアプリケーションでは、アプリケーションが開いているときは現在の場所の緯度と経度を取得しますが、アプリケーションを閉じているときは取得しません。
Service クラスを使用して、アプリケーションで現在の場所の緯度と経度を取得しています。
アプリを閉じても現在地の緯度経度を取得する方法を教えてください
私のアプリケーションでは、アプリケーションが開いているときは現在の場所の緯度と経度を取得しますが、アプリケーションを閉じているときは取得しません。
Service クラスを使用して、アプリケーションで現在の場所の緯度と経度を取得しています。
アプリを閉じても現在地の緯度経度を取得する方法を教えてください
数か月前に、GPS 位置情報を取得するのに役立つ GPSTracker ライブラリを作成しました。GPSTracker > getLocation を表示する必要がある場合
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
アクティビティ
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo_locations);
// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);
String country = gpsTracker.getCountryName(this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText(country);
String city = gpsTracker.getLocality(this);
textview = (TextView)findViewById(R.id.fieldCity);
textview.setText(city);
String postalCode = gpsTracker.getPostalCode(this);
textview = (TextView)findViewById(R.id.fieldPostalCode);
textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText(addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
return true;
}
}
GPSトラッカー
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
/**
* Create this Class from tutorial :
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
*
* For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
*
*/
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* @return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* @return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
方法/答えがうまくいかない場合。 公式の Google プロバイダーであるFusedLocationProviderApiを使用する必要があります。
ロケーションリスナーメソッドを使用
@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}
次のクラスをサービス クラスとして使用して、アプリケーションをバックグラウンドで実行できます。
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private GPSTracker gpsTracker;
private Handler handler= new Handler();
private Timer timer = new Timer();
private Distance pastDistance = new Distance();
private Distance currentDistance = new Distance();
public static double DISTANCE;
boolean flag = true ;
private double totalDistance ;
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
if(flag){
pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = false;
}else{
currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = comapre_LatitudeLongitude();
}
Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
}
});
}
};
timer.schedule(timerTask,0, 5000);
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--------------------------------onDestroy -stop service ");
timer.cancel();
DISTANCE = totalDistance ;
}
public boolean comapre_LatitudeLongitude(){
if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
return false;
}else{
final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
System.out.println("Distance in mile :"+distance);
handler.post(new Runnable() {
@Override
public void run() {
float kilometer=1.609344f;
totalDistance = totalDistance + distance * kilometer;
DISTANCE = totalDistance;
//Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
}
});
return true;
}
}
}
場所を取得するために別のクラスを追加します
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
private Location m_Location;
public GPSTracker(Context context) {
this.mContext = context;
m_Location = getLocation();
System.out.println("location Latitude:"+m_Location.getLatitude());
System.out.println("location Longitude:"+m_Location.getLongitude());
System.out.println("getLocation():"+getLocation());
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@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
}
}
// --------------Distance.java
public class Distance {
private double latitude ;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
これは、Google アカウントやサブスクリプションを使用せずに現在地を見つけることができる Android 位置情報ライブラリです。
このリンクを見つけてリポジトリをダウンロード
https://github.com/mrmans0n/smart-location-lib
気をつけて楽しんでください...
これを試してみてください。場所が変わるたびに現在の場所を取得するのに役立つことを願っています.
public class MyClass implements LocationListener {
double currentLatitude, currentLongitude;
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
}