onLactionChanged从未调用过(fusedLocationApi)

时间:2015-08-17 12:40:41

标签: android

我有位置跟踪器应用程序,并且有一个类,处理位置更改。 4.2.2设备正常工作 - onLocationChanged()回调响应。但在其他设备上 - lollypop - 相同的代码从不调用onLocationChanged()。尝试使用GPS启用/禁用以及启用/禁用互联网。在应用程序运行时期间打开/关闭GPS模块不会改变任我不知道,在哪里可以找到解决这个问题的方法。请帮助。

package kgk.tracker;


import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import de.greenrobot.event.EventBus;
import kgk.tracker.messages.GPS;

public class LocationProvider implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        GpsStatus.Listener {

    public static final String TAG = LocationProvider.class.getSimpleName();
    public final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private static LocationProvider locationProvider;

    // Объект - клиент сервиса Google Play
    private GoogleApiClient googleApiClient;

    // Параметры запроса на предоставление координат для Google Play
    private LocationRequest locationRequest;

    // Объект LocationManager для определения количества используемых спутников
    private LocationManager locationManager;
    private static int satellitesCount = 0;

    // Конструкторы

    private LocationProvider() {
        locationManager = (LocationManager) KGKTracker.getAppContext().getSystemService(Context.LOCATION_SERVICE);
        locationManager.addGpsStatusListener(this);
        createLocationRequest();
        buildGoogleApiClient();
        EventBus.getDefault().register(this);

        android.location.LocationListener locationListener = new android.location.LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Используется другая реалзиация данного метода в библиотеке FusedLocationApi
            }

            @Override
            public void onProviderDisabled(String arg0) {
                Log.d("GPS", "Provider disabled");
                kgk.tracker.LocationProvider.setSatellitesCount(0);
                CommunicationService.setGps_enabled(false);
                CommunicationService.getCommunicationService().generateEmptyPacket();
                CommunicationService.getCommunicationService().gpsLost();
            }

            @Override
            public void onProviderEnabled(String arg0) {
                Log.d("GPS", "Provider enabled");
                CommunicationService.setGps_enabled(true);
                CommunicationService.getCommunicationService().generateEmptyPacket();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle arg2) {
                Log.d("GPS STATUS", "STATUS CHANGED");
                switch (status) {
                    case android.location.LocationProvider.AVAILABLE:
                        Log.d("GPS STATUS", "AVAILABLE");
                        //gpsFound();
                        break;
                    default:
                        Log.d("GPS STATUS", "LOST");
                        //gpsLost();
                        break;
                }
            }
        };
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
    }

    public static LocationProvider getInstance() {
        if (locationProvider == null) {
            return new LocationProvider();
        } else {
            return locationProvider;
        }
    }

    // Аксессоры

    public static int getSatellitesCount() {
        return satellitesCount;
    }

    public static void setSatellitesCount(int satellitesCount) {
        LocationProvider.satellitesCount = satellitesCount;
    }

    public GoogleApiClient getGoogleApiClient() {
        return googleApiClient;
    }

    // Открытые методы

    /**
     * Обработка ивента с помощью библиотеки EventBus
     */
    public void onEvent(LocationEvent locationEvent) {
        if (locationEvent.getDoConnect()) {
            if (!googleApiClient.isConnected()) {
                googleApiClient.connect();
            }
        } else {
            googleApiClient.disconnect();
        }
    }

    // Внутренние методы

    /**
     * Создание объекта GoogleApiClient
     */
    private synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(KGKTracker.getAppContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Создание LocationRequest
     */
    private void createLocationRequest() {
        locationRequest = LocationRequest.create()
                .setInterval(5000)
                .setFastestInterval(5000)
                .setSmallestDisplacement(0.0f)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    /**
     * Возвращает количество используемых спутников
     */
    private int checkSatellitesCount() {
        int satellitesInUse = 0;
        for (GpsSatellite satellite : locationManager.getGpsStatus(null).getSatellites()) {
            if (satellite.usedInFix()) {
                satellitesInUse++;
            }
        }

        return satellitesInUse;
    }

    // Реализация интерфейсов

    @Override
    public void onConnected(Bundle bundle) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        switch (i) {
            case CAUSE_SERVICE_DISCONNECTED:
                Log.d(TAG, "CAUSE_SERVICE_DISCONNECTED");
                break;
            case CAUSE_NETWORK_LOST:
                Log.d(TAG, "CAUSE_SERVICE_DISCONNECTED");
                break;
            default:
                Log.d(TAG, "Unknown reason");
                break;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed  " + connectionResult);

        if (connectionResult.getErrorCode() ==  ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.getMainActivity());
            GooglePlayServicesUtil.getErrorDialog(resultCode, MainActivity.getMainActivity(), PLAY_SERVICES_RESOLUTION_REQUEST).show();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Current location at: " + location.getLatitude() + "   " + location.getLongitude() + "   " + satellitesCount);

        CommunicationService service = CommunicationService.getCommunicationService();

        if (service != null) {
            service.setLastPacket(new Packet(location));
            long last_packet_id = DB.getInstance(KGKTracker.getAppContext()).write_packet(service.getLastPacket());
            service.getLastPacket().setId(last_packet_id);
            service.gpsFound();
            try {
                service.getMessageQueue().put(new GPS(service.getLastPacket()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onGpsStatusChanged(int event) {
        switch (event) {
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                satellitesCount = checkSatellitesCount();
                break;
            default:
                Log.d(TAG, "Unexpected behavior in onGpsStatusChanged callback");
                break;
        }
    }
}

0 个答案:

没有答案