Android服务不更新位置 [英] Android Service not updating location

查看:165
本文介绍了Android服务不更新位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每1分钟和每5米位移更新融合位置(我知道它的不良做法,但为了测试和显示在日志中)我开始服务按钮按下按钮我得到位置在logcat但只有一次。根据服务等级 onLocationChanged 应该每隔1分钟调用一次但是它几乎不会再次呼叫,即使我的GPS几乎每分钟开启一次,然后在关机后关闭,但仍然没有位置在Logcat中更新。我需要服务类来保持更新位置而不影响UI或主线程

I need to update fused location every 1 min and on each 5 meter displacement (I know its bad practice but for the sake of testing and showing in Log ) and i start service by button Pressed as soon as button pressed i got location in logcat but only once. As per Service class the onLocationChanged should called every 1 min but it never calls again even my GPS turn on almost every min and then turn off after while but still there is no Location Update in Logcat.I need service class to keep update location without effecting UI or main thread

这是logcat,它只显示一次位置更新

09-16 03:13:37.125 10419-10419/com.example.com.pro_working1 D/===Location Service===: Service onConnected Calling
09-16 03:13:37.125 10419-10419/com.example.com.pro_working1 D/===Location Service===: Start Location Update is Calling
09-16 03:13:38.315 10419-10419/com.example.com.pro_working1 D/===Location Service===: Service OnLocationChanged Calling
09-16 03:13:38.315 10419-10419/com.example.com.pro_working1 D/===Location Service===: Here is Updated Locations: Latitude 28.5XXXXX Longitude 77.2XXXXX
09-16 03:13:38.315 10419-10419/com.example.com.pro_working1 D/===Location Service===: Sending Location Starting  Accuracy is: 37.5

这是我的服务类

public class Location_Service_background extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    public static final String TAG = "===Location Service===";
    GoogleApiClient apiClient;
    Location mCurrentLocation;
    LocationRequest locationRequest;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        GoogleApiSetup();
        RequestLocationUpdates();
        Log.d(TAG,"OnStartCommand Is Calling ");
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }



    @Override
    public void onCreate() {
        super.onCreate();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (apiClient.isConnected()){
            Log.d(TAG,"Service On Destroy Calling and apiClient is Connected");
            StopLocationUpdates();
            apiClient.disconnect();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d(TAG,"Service onConnected Calling");
        if (mCurrentLocation != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
             mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);

        }
        else {
            Log.d(TAG,"Start Location Update is Calling");
            StartLocationUpdate();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d(TAG,"Service OnConnectionSuspended Calling");
        apiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG,"Service OnLocationChanged Calling");
        mCurrentLocation=location;
        Log.d(TAG,"Here is Updated Locations: Latitude "+mCurrentLocation.getLatitude()+"Longitude "+mCurrentLocation.getLongitude());
        String Latitude= String.valueOf(mCurrentLocation.getLatitude());
        String Longitude=String.valueOf(mCurrentLocation.getLongitude());
        String Accuracy=String.valueOf(mCurrentLocation.getAccuracy());
        Log.d(TAG,"Sending Location Starting"+" "+" Accuracy is: "+mCurrentLocation.getAccuracy());


    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG,"Connection Failed Called "+connectionResult);
    }



    private synchronized  void GoogleApiSetup() {
        apiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        apiClient.connect();
    }

    private void RequestLocationUpdates() {
        locationRequest = new LocationRequest();
        //1 Min = 60 seconds AND 1000 milliseconds in 1 second
        locationRequest.setInterval(60 * 1000);//5 Min 300 x 1000=300000
        locationRequest.setFastestInterval(60 * 1000);//2 Min
        locationRequest.setSmallestDisplacement(5);
        locationRequest.setMaxWaitTime(60*1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    private void StopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, this);
    }

    private void StartLocationUpdate() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        if (apiClient.isConnected()) {
            LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
        }
        else {
            Log.d(TAG,"GoogleApiClient is not connected yet.Please Try Again");
            apiClient.connect();
        }
    }


}


推荐答案

希望这有助于拯救某人在此问题上遇到的挫败感。我正在使用FusedLocationAPI来请求位置更新和GoogleApiClient。我也是从服务中执行此操作。

Hopefully this helps save someone the frustration i went through on this issue. I am using the FusedLocationAPI to request location updates and GoogleApiClient. I also do this from a Service.

您没有在您的定时间隔获得任何位置更新,因为setSmallestDisplacement()优先于其他参数。所以即使你有

You are not getting any location updates at your timed interval because setSmallestDisplacement() takes absolute priority over the other parameters. So even if you have

locationRequestTimeInterval = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(1)    
    .setFastestInterval(1)    
    .setMaxWaitTime(1)    
    .setSmallestDisplacement(5);

除非满足minimumDisplacement参数,否则不会触发。

this will NEVER be triggered until the smallestDisplacement parameter is met.

对此的解决方案是创建两个单独的LocationRequests ...一个仅关注距离,一个仅关注时间,并使用您的单个GoogleApiClient创建2个requestLocationUpdates命令,一个使用Time LocationRequest,另一个使用Distance LocationRequest。

The solution to this, is to create two separate LocationRequests... one that is only concerned with distance, and one that is only concerned with time, and use your single GoogleApiClient to create 2 requestLocationUpdates commands, one using the Time LocationRequest, and the other using the Distance LocationRequest.

所以你的2个LocationRequests看起来像这样:

So your 2 LocationRequests look like this:

locationRequestDistanceInterval = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setFastestInterval(0) // This MUST be set, otherwise no updates
            .setSmallestDisplacement(LOCATION_REQUEST_MIN_DISTNACE);

locationRequestTimeInterval = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(PROVIDER_GPS_UPDATE_TIME_INTERVAL)
            .setFastestInterval(PROVIDER_GPS_UPDATE_TIME_INTERVAL);




  • 请注意,必须在距离请求上设置setFastestInterval()值否则不会触发距离请求。它不必为0,但必须设置此字段。

  • 然后在您的GoogleApiClients onConnected()中,您可以添加两个requestLocationUpdates()调用。

    Then in your GoogleApiClients onConnected(), you can add the two requestLocationUpdates() calls.

    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, locationRequestDistanceInterval, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Handle your Distance based updates
            });
        LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, locationRequestTimeInterval, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Handle your Time based updates
            }
        }); 
    

    您可以使用相同或单独的LocationListeners来处理每个请求的响应。
    希望这有帮助。

    You can use the same or separate LocationListeners to handle the responses for each request. Hope this helps.

    这篇关于Android服务不更新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆