android– 在30秒内获得纬度和经度

android– 在30秒内获得纬度和经度,第1张

概述我试图获得用户的位置作为经常可用的GPS/网络的经度纬度,我想快速得到它,否则如果现在无法获得新的位置坐标将返回.这是我的尝试:publicclassGPSTrackerextendsService{//TheminimumdistancetochangeUpdatesinmetersprivatestaticfinallongMIN_DI

我试图获得用户的位置作为经常可用的GPS /网络的经度和纬度,我想快速得到它,否则如果现在无法获得新的位置坐标将返回.

这是我的尝试:

public class GPSTracker extends Service{    // 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    private final Context mContext;    // Declaring a Location Manager    protected LocationManager locationManager;    // flag for GPS status    boolean isGPSEnabled = false;    // flag for network status    boolean isNetworkEnabled = false;    // flag for GPS status    boolean canGetLocation = false;    Location location = null; // location    double latitude; // latitude    double longitude; // longitude    myLocationlitener locationlitener;    public GPSTracker(Context context) {        this.mContext = context;        locationlitener = new myLocationlitener();        getLocation();    }    public Location 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);            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,locationlitener);                    Log.d("Network", "Network Enabled");                    if (locationManager != null) {                        location = locationManager                                .getLastKNownLocation(LocationManager.NETWORK_PROVIDER);                        if (location != null) {                            latitude = location.getLatitude();                            longitude = location.getLongitude();                        }                    }                }                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {                    if (location == null) {                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {                            // Todo: ConsIDer calling                            //    ActivityCompat#requestPermissions                            // here to request the missing permissions, and then overrIDing                            //   public voID onRequestPermissionsResult(int requestCode, String[] permissions,                            //                                          int[] grantResults)                            // to handle the case where the user grants the permission. See the documentation                            // for ActivityCompat#requestPermissions for more details.                            return null;                        }                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_disTANCE_CHANGE_FOR_UPDATES, locationlitener);                        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;    }    /**     * Stop using GPS Listener Calling this function will stop using GPS in your     * app     */    public voID stopUsingGPS() {        if (locationManager != null) {            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {                // Todo: ConsIDer calling                //    ActivityCompat#requestPermissions                // here to request the missing permissions, and then overrIDing                //   public voID onRequestPermissionsResult(int requestCode, String[] permissions,                //                                          int[] grantResults)                // to handle the case where the user grants the permission. See the documentation                // for ActivityCompat#requestPermissions for more details.                return;            }            locationManager.removeUpdates(locationlitener);        }    }    /**     * Function to get latitude     */    public double getLatitude() {        if (location != null) {            latitude = location.getLatitude();        }        // return latitude        return latitude;    }    /**     * Function to get longitude     */    public double getLongitude() {        if (location != null) {            longitude = location.getLongitude();        }        // return longitude        return longitude;    }    /**     * Function to check GPS/wifi enabled     *     * @return boolean     */    public boolean canGetLocation() {        return this.canGetLocation;    }    /**     * Function to show settings alert dialog On pressing Settings button will     * lauch Settings Options     */    public voID showSettingsAlert() {        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);        // Setting Dialog Title        alertDialog.setTitle("GPS is settings");        // Setting Dialog Message        alertDialog                .setMessage("GPS is not enabled. Do you want to go to settings menu?");        // On pressing Settings button        alertDialog.setPositivebutton("Settings",                new DialogInterface.OnClickListener() {                    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("Cancel",                new DialogInterface.OnClickListener() {                    public voID onClick(DialogInterface dialog, int which) {                        dialog.cancel();                    }                });        // Showing Alert Message        alertDialog.show();    }    @OverrIDe    public IBinder onBind(Intent arg0) {        return null;    }    private class myLocationlitener implements LocationListener{        @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) {        }    }}

我怎么用这堂课?

假设我在异步任务中运行下面的函数(谁不知道androID注释@Background正在这样做)

 @Background    voID getmyLocationAndSend(){        GPSTracker gps = new GPSTracker(context);        // check if GPS location can get Location        if (gps.canGetLocation()) {            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);            if (locationManager.isProvIDerEnabled(LocationManager.NETWORK_PROVIDER)) {                Log.d("Your Location", "latitude:" + gps.getLatitude()                        + ", longitude: " + gps.getLongitude());                latitude = gps.getLatitude(); // set the globals                longitude = gps.getLongitude(); // set the globals            }else{                showToast("Network is connected..");                if (progress != null && progress.isShowing()) {                    progress.dismiss();                }            }        }else{            showToast("Cannot get location from gps..");            if (progress != null && progress.isShowing()) {                progress.dismiss();            }        }    }

我的目标是在不到30秒内获得坐标,永远不会得到0.0值,我怎样才能实现任何帮助?

解决方法:

请检查我在我的应用程序中的使用方式及其完美的工作方式.我使用融合API进行更新,请按照几个步骤进行 *** 作.目前您使用的是非常古老的方法.所以,现在没有必要
并以毫秒为单位传递你想要的时间
UPDATE_INTERVAL_IN_MILliSECONDS

第1步.上课
GoogleLocationService.java

public class GoogleLocationService {private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();LocationUpdateListener locationUpdateListener;Context activity;protected Googleapiclient mGoogleapiclient;protected LocationRequest mLocationRequest;public static final long UPDATE_INTERVAL_IN_MILliSECONDS = 30000;public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {    this.locationUpdateListener = locationUpdateListener;    this.activity = activity;    buildGoogleapiclient();}protected synchronized voID buildGoogleapiclient() {    //Log.i(TAG, "Building Googleapiclient");    mGoogleapiclient = new Googleapiclient.Builder(activity)            .addConnectionCallbacks(callbacks)            .addOnConnectionFailedListener(callbacks)            .addAPI(LocationServices.API)            .build();    createLocationRequest();    mGoogleapiclient.connect();}protected voID createLocationRequest() {    mLocationRequest = new LocationRequest();    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILliSECONDS);    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);}private class GoogleServicesCallbacks implements Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener, LocationListener {    @OverrIDe    public voID onConnected(Bundle bundle) {        startLocationUpdates();    }    @OverrIDe    public voID onConnectionSuspended(int i) {        mGoogleapiclient.connect();    }    @OverrIDe    public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) {        if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_required) {            Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();        }        locationUpdateListener.cannotReceiveLocationUpdates();    }    @OverrIDe    public voID onLocationChanged(Location location) {        if (location.hasAccuracy()) {            if (location.getAccuracy() < 30) {                locationUpdateListener.updateLocation(location);            }        }    }}private static boolean locationEnabled(Context context) {    boolean gps_enabled = false;    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);    try {        gps_enabled = lm.isProvIDerEnabled(LocationManager.GPS_PROVIDER);    } catch (Exception ex) {        ex.printstacktrace();    }    return gps_enabled;}private boolean servicesConnected(Context context) {    return isPackageInstalled(GooglePlayServicesUtil.Google_PLAY_STORE_PACKAGE, context);}private boolean isPackageInstalled(String packagename, Context context) {    PackageManager pm = context.getPackageManager();    try {        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);        return true;    } catch (PackageManager.nameNotFoundException e) {        e.printstacktrace();        return false;    }}public voID startUpdates() {    /*     * Connect the clIEnt. Don't re-start any requests here; instead, wait     * for onResume()     */    if (servicesConnected(activity)) {        if (locationEnabled(activity)) {            locationUpdateListener.canReceiveLocationUpdates();            startLocationUpdates();        } else {            locationUpdateListener.cannotReceiveLocationUpdates();            Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();        }    } else {        locationUpdateListener.cannotReceiveLocationUpdates();        Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();    }}//stop location updatespublic voID stopUpdates() {    stopLocationUpdates();}//start location updatesprivate voID startLocationUpdates() {    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {        return;    }    if (mGoogleapiclient.isConnected()) {        LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, callbacks);    }}public voID stopLocationUpdates() {    if (mGoogleapiclient.isConnected()) {        LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleapiclient, callbacks);    }}public voID startGoogleAPI() {    mGoogleapiclient.connect();}public voID closeGoogleAPI() {    mGoogleapiclient.disconnect();} }

第2步.制作这个界面
LocationUpdateListener.java

 public interface LocationUpdateListener {/** * Called immediately the service starts if the service can obtain location */voID canReceiveLocationUpdates();/** * Called immediately the service trIEs to start if it cannot obtain location - eg the user has Disabled wireless and */voID cannotReceiveLocationUpdates();/** * Called whenever the location has changed (at least non-trivially) * @param location */voID updateLocation(Location location);/** * Called when GoogleLocationServices detects that the device has moved to a new location. * @param localityname The name of the locality (somewhere below street but above area). */voID updateLocationname(String localityname, Location location);}

第3步.制作此位置服务类
LocationService.java

public class LocationService extends Service {private GoogleLocationService GoogleLocationService;@OverrIDepublic voID onCreate() {    super.onCreate();    //start the handler for getting locations    //create component    updateLocation(getApplicationContext());}@OverrIDepublic int onStartCommand(Intent intent, int flags, int startID) {    return Service.START_STICKY;}//get current location os userprivate voID updateLocation(Context context) {    GoogleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {        @OverrIDe        public voID canReceiveLocationUpdates() {        }        @OverrIDe        public voID cannotReceiveLocationUpdates() {        }        //update location to our servers for tracking purpose        @OverrIDe        public voID updateLocation(Location location) {            if (location != null ) {                Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());            }        }        @OverrIDe        public voID updateLocationname(String localityname, Location location) {            GoogleLocationService.stopLocationUpdates();        }    });    GoogleLocationService.startUpdates();}IBinder mBinder = new LocalBinder();public class LocalBinder extends Binder {    public LocationService getServerInstance() {        return LocationService.this;    }}@OverrIDepublic IBinder onBind(Intent intent) {    return mBinder;}//stop location updates on stopPing the service@OverrIDepublic voID onDestroy() {    super.onDestroy();    if (GoogleLocationService != null) {        GoogleLocationService.stopLocationUpdates();    }}}

编辑答案:

如何使用服务,

在您的主要活动中启动服务,如下所示

startService(new Intent(context, LocationService.class));

停止,

stopService(new Intent(context, LocationService.class));

并在清单中声明,

<service androID:name=".service.location.LocationService" androID:enabled="true"></service>

注意:我这样做是因为我在杀死app后需要位置.如果你不想要服务.那么,你可以直接在类中需要更新位置的代码下面调用并删除locationservice.

 private GoogleLocationService GoogleLocationService; GoogleLocationService = new GoogleLocationService(context, new LocationUpdateListener() {    @OverrIDe    public voID canReceiveLocationUpdates() {    }    @OverrIDe    public voID cannotReceiveLocationUpdates() {    }    //update location to our servers for tracking purpose    @OverrIDe    public voID updateLocation(Location location) {        if (location != null ) {            Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude());        }    }    @OverrIDe    public voID updateLocationname(String localityname, Location location) {        GoogleLocationService.stopLocationUpdates();    }});GoogleLocationService.startUpdates();and call this onDestroy if (GoogleLocationService != null) {    GoogleLocationService.stopLocationUpdates();}

记住,Locationservice也应该在清单中声明.
据我说这是最好的解决方案.我在现场做了很多工作.
谢谢希望这会对你有所帮助

总结

以上是内存溢出为你收集整理的android – 在30秒内获得纬度和经度全部内容,希望文章能够帮你解决android – 在30秒内获得纬度和经度所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1104078.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存