0
我想在應用程序關閉時檢測用戶用戶在後臺的活動。有一個使用Google API for Android的ActivityRecognition的例子。 在示例中,識別是由一個活動啓動的,並且我使服務得以實現。 它可以在大多數設備上正常工作,但不能在使用api 4.2.x的設備上正常工作。android在後臺檢測ActivityRecognition
public class RecognitionService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ResultCallback<Status> {
private static final String TAG = RecognitionService.class.getSimpleName();
public final static int DETECTION_INTERVAL_IN_MILLISECONDS = 60_000;
private GoogleApiClient googleApiClient;
public RecognitionService() {
super();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
initLocationClient();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void initLocationClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient
.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.build();
}
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
}
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to GoogleApiClient");
if (googleApiClient != null && googleApiClient.isConnected()) {
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
googleApiClient,
DETECTION_INTERVAL_IN_MILLISECONDS,
getActivityDetectionPendingIntent()
).setResultCallback(this);
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
googleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
private PendingIntent getActivityDetectionPendingIntent() {
Intent intent = new Intent(this, DetectedActivitiesIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// requestActivityUpdates() and removeActivityUpdates().
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onResult(Status status) {
Log.i(TAG, "onResult = " + status.getStatusMessage());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(
googleApiClient,
getActivityDetectionPendingIntent()
).setResultCallback(this);
}
}
onConnected,onConnectionSuspended,onConnectionFailed方法不會被調用。
對這種情況你有什麼想法嗎?使用isGooglePlayServicesAvailable()安裝的設備具有GooglePlayServices的正確版本
感謝您的回答,GooglePlayServices是正確的 –
因此調用'googleApiClient.connect()'並且根本沒有回調? logcat中有什麼? –