【问题标题】:Send GPS coordinates periodically定期发送 GPS 坐标
【发布时间】:2016-09-18 13:50:04
【问题描述】:

我是一名 Windows 应用程序程序员,最近开始学习 android。我计划制作一个应用程序,在单击“开始”按钮后每 30 秒定期发送 GPS 坐标,并通过单击“停止”按钮停止发送(我已经开发了一个接受数据的网络服务)。在 Windows 中,我会使用计时器,并且在每个“滴答”上都会找到 GPS 坐标并发送它。请帮助理解如何在 android 中完成类似的事情。

【问题讨论】:

    标签: android gps


    【解决方案1】:

    请检查我在我的应用程序中的使用情况及其完美运行。我正在使用 fused api 获取更新位置,请按照几个步骤操作。

    步骤 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 updates
    public void stopUpdates() {
        stopLocationUpdates();
    }
    
    //start location updates
    private 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();
    }
    
     }
    

    第二步。制作这个界面 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 步。在您的 oncreate 上调用它

    私有的 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();
    }
    

    希望这能帮助您解决问题。

    【讨论】:

    • 您实际在哪里开始和停止?
    • 你能看一下第3步吗
    • 在 windows XNA 中可以进行计时,但在 android 中您必须使用警报管理器。检查它stackoverflow.com/questions/4459058/alarm-manager-example>。
    • 如果你想在杀死应用程序后获取位置然后使用服务
    【解决方案2】:

    查看RxGpsService(使用 RxJava 检索 GPS 位置和路线统计信息的 Android 服务)。它检索一个RouteStats 对象,其中包含当前速度、距离、经过的时间和航路点。您也可以播放/停止计时,以便在计时停止时丢弃位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多