Не может получить доступ к GoogleApilClient.onConnectionCallback

Я пытаюсь написать библиотеку timelocLib, которая будет выбирать местоположение с помощью API местоположения Google. Класс провайдера местоположения в timeloclib подключается к клиенту Google и реализует обратные вызовы GoogleClientApi.

LocationProvider:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.util.ArrayList;
import java.util.Iterator;

import static android.content.Context.LOCATION_SERVICE;

/**
 * Created by Hashim Ali on 3/4/2018.
 */

public class LocationProvider implements     GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener,
    ResultCallback<Status> {
private static final String TAG = LocationProvider.class.getSimpleName();
private Context mContext;
private LocationManager mLocationManager;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastKnwonLocation;
private int mSateliteCount = -1;
private String mActivityRecognitionString = "";
private int mLocationRequestPriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
private long mLocationRequestInterval = 2000;
private ActivityDetectionBroadcastReceiver mActRecogBroadcastReceiver;
private ResultReceiver mAddressResultReciever = null;

public LocationProvider(Context context) {
    mContext = context;
    mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
    mActRecogBroadcastReceiver = new ActivityDetectionBroadcastReceiver();
}

@SuppressLint("MissingPermission")
@Override
public void onConnected(@Nullable Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setPriority(mLocationRequestPriority);
    mLocationRequest.setInterval(mLocationRequestInterval);
    //TODO: use FusedLocationProviderClient instead of FusedLcoationApi with google Api upgrade 12.0.0. (Hashim 4/March)
    // Reference: https://stackru.com/questions/46481789/android-locationservices-fusedlocationapi-deprecated
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    requestGnssStatusUpdates();
    requestActivityRecognitionUpdates();
}

@Override
public void onConnectionSuspended(int i) {
    Log.w(TAG, "onConnectionSuspended: connection suspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "onConnectionFailed: connection Failed");
}

@Override
public void onLocationChanged(Location location) {
    mLastKnwonLocation = location;
    Bundle updatedLocationBundle = mLastKnwonLocation.getExtras();
    updatedLocationBundle.putInt(TimeLocConstants.BUNDLE_EXTRA_SATELLITE_COUNT, mSateliteCount);
    updatedLocationBundle.putString(TimeLocConstants.BUNDLE_EXTRA_ACTIVITY_RECOGNITION_STRING, mActivityRecognitionString);
    mLastKnwonLocation.setExtras(updatedLocationBundle);
}

@Override
public void onResult(@NonNull Status status) {
    if (status.isSuccess()) {
        Log.d(TAG, "ResultCallBack<Status>: Successfully added activity detection.");

    } else {
        Log.e(TAG, "ResultCallBack<Status>: Error adding or removing activity detection: " + status.getStatusMessage());
    }
}

@SuppressLint("MissingPermission")
private void requestGnssStatusUpdates() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Log.d(TAG, "onResume: Build version >= N using GnssStatus.Callback, for satellite updates");
        //mGnssCallback = new GnssStatus.Callback(); if NoClassFoundError use this line
        mLocationManager.registerGnssStatusCallback(mGnssCallback);
    } else {
        Log.d(TAG, "onResume: Build version < N using GpsStatusListener, for satellite updates");
        mLocationManager.addGpsStatusListener(mGpsStatusListener);
    }
}

private void removeGnssStatusUpdates() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Log.d(TAG, "onPause: unregistering gnss status call back");
        mLocationManager.unregisterGnssStatusCallback(mGnssCallback);
    } else {
        Log.d(TAG, "onPause: unregistering gps status call back");
        mLocationManager.removeGpsStatusListener(mGpsStatusListener);
    }
}

private void requestActivityRecognitionUpdates() {
    if (!mGoogleApiClient.isConnected()) {
        Log.e(TAG, "requestActivityRecognitionUpdates: google api client not initialized");
        return;
    }
    //TODO: remove this deprecated api. (Hashim 4/March)
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
            mGoogleApiClient,
            mLocationRequestInterval,
            getActivityDetectionPendingIntent()
    ).setResultCallback(this);
}

private void removeActivityRecognitionUpdates() {
    if (!mGoogleApiClient.isConnected()) {
        Log.e(TAG, "requestActivityRecognitionUpdates: google api client not initialized");
        return;
    }
    ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(
            mGoogleApiClient,
            getActivityDetectionPendingIntent()
    ).setResultCallback(this);
}

private PendingIntent getActivityDetectionPendingIntent() {
    Intent intent = new Intent(mContext, ActivityRecogAndAddressService.class);
    intent.putExtra(TimeLocConstants.LOCAL_BROADCAST_ACTION, TimeLocConstants.LOCAL_BROADCAST_EXTRA_ACTION_GET_ACT_RECOG);
    return PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

private boolean checkPermissions() {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }
    return true;
}

public void setLocationRequestPriority(int mLocationRequestPriority) {
    this.mLocationRequestPriority = mLocationRequestPriority;
}

public void setLocationRequestInterval(long mLocationRequestInterval) {
    this.mLocationRequestInterval = mLocationRequestInterval;
}

public void initGoogleApiClient() {
    if (!checkPermissions()) {
        Log.e(TAG, "initGoogleApiClient: permissions not granted");
        return;
    }
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(LocationServices.API)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

public void connectGoogleApiClient() {
    mGoogleApiClient.connect();
}

public void disconnectGoogleApiClient() {
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
        removeGnssStatusUpdates();
        removeActivityRecognitionUpdates();
    }
}

public Location getLastKnownLocation() {
    return mLastKnwonLocation;
}

public void requestAddressStringAndListenForResult(ResultReceiver clientResultReciever) {
    mAddressResultReciever = clientResultReciever;
    Intent intent = new Intent(mContext, ActivityRecogAndAddressService.class);
    intent.putExtra(TimeLocConstants.LOCAL_BROADCAST_ACTION, TimeLocConstants.LOCAL_BROADCAST_EXTRA_ACTION_GET_ADDRESS);
    intent.putExtra(TimeLocConstants.LOCAL_BROADCAST_EXTRA_RECEIVER, clientResultReciever);
    intent.putExtra(TimeLocConstants.LOCAL_BROADCAST_EXTRA_LOCATION_DATA, mLastKnwonLocation);
    //TODO: start foreground service or move this code to asyncTask. (Hashim 4/March)
    mContext.startService(intent);
}

private GpsStatus.Listener mGpsStatusListener = new GpsStatus.Listener() {
    @Override
    public void onGpsStatusChanged(int i) {
        @SuppressLint("MissingPermission") GpsStatus gpsStatus = mLocationManager.getGpsStatus(null);
        if (gpsStatus != null) {
            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            int satelliteCount = 0;
            while (sat.hasNext()) {
                satelliteCount++;
                sat.next();
            }
            mSateliteCount = satelliteCount;
        }
    }
};

@RequiresApi(api = Build.VERSION_CODES.N)
private GnssStatus.Callback mGnssCallback = new GnssStatus.Callback() {
    @Override
    public void onStarted() {
        Log.d(TAG, "gnssStatusCallBack: on started");
    }

    @Override
    public void onStopped() {
        Log.d(TAG, "gnssStatusCallBack: on stopped");
    }

    @Override
    public void onFirstFix(int ttffMillis) {
        Log.d(TAG, "gnssStatusCallBack: first fix it took " + ttffMillis + " millis before first gnss update");
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onSatelliteStatusChanged(GnssStatus status) {
        mSateliteCount = status.getSatelliteCount();
        Log.d(TAG, "gnssStatusCallBack: satellite status changed: " + mSateliteCount);
    }
};

private class ActivityDetectionBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "ActivityDetectionBroadcastReceiver: onReceive: " + intent.toString());
        ArrayList<DetectedActivity> updatedActivities =
                intent.getParcelableArrayListExtra(TimeLocConstants.LOCAL_BROADCAST_EXTRA_ACTIVITIES);
        String actRecogString = "";
        for (DetectedActivity thisActivity : updatedActivities) {
            actRecogString += getActivityString(thisActivity.getType()) + thisActivity.getConfidence() + "%\n";
        }
        mActivityRecognitionString = actRecogString;
    }

    private String getActivityString(int detectedActivityType) {
        switch (detectedActivityType) {
            case DetectedActivity.IN_VEHICLE:
                return "in vehicle";
            case DetectedActivity.ON_BICYCLE:
                return "on bicycle";
            case DetectedActivity.ON_FOOT:
                return "on foot";
            case DetectedActivity.RUNNING:
                return "running";
            case DetectedActivity.STILL:
                return "still";
            case DetectedActivity.TILTING:
                return "tilting";
            case DetectedActivity.UNKNOWN:
                return "unknown";
            case DetectedActivity.WALKING:
                return "walking";
            default:
                return "unidentifiable activity";
        }
    }


}

}

Я не получаю никаких ошибок кода при сборке gradle, но когда я пытаюсь вызвать методы LocationProvider в MainActivity, я получаю ошибку:

невозможно получить доступ к com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks

Gradle для timeloclib:

apply plugin: 'com.android.library'

android {compileSdkVersion 26

defaultConfig {
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-location:11.8.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile project(path: ':library')
}

и Manifest.xml для timeloclib это:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.resatech.android.timeloclib">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

<application>
    <meta-data
        android:name="com.google.android.gms.versions"
        android:value="@integer/google_play_services_version" />
    <service
        android:name=".ActivityRecogAndAddressService"
        android:exported="false" />
</application>

Буду благодарен за любую помощь!

0 ответов

Другие вопросы по тегам