2

googleApiClient.connect()가 호출 될 때 아래 코드와 같이 GoogleApiClient의 ActivityRecognition.ActivityRecognitionApi를 사용하여 requestActivityUpdates()를 말하면 'ActivityTrackerService'서비스가 호출됩니다. API가 연결되면 onConnected 콜백이 실행되고 작업 업데이트가 요청됩니다. 결과 호출 에서처럼 코드가 완벽하게 실행되어 성공을 거둔다. 하지만 Service 클래스 onHandleIntent가 호출되지 않는 방법도 있습니다. 서비스가 작동하는지 여부는 확실하지 않습니다.ActivityRecognitionClient가 아닌 com.google.android.gms.common.api.GoogleApiClient를 사용하여 Android에서 ActivityUpdates를 요청하는 방법은 무엇인가요?

서비스 공급자 클래스 :

public class ActivityServiceProvider { 
    private Context context; 
    private GoogleApiClient googleApiClient; 
    private PendingIntent mActivityRecognitionPendingIntent; 

    public ActivityServiceProvider(Context context) { 
     this.context = context; 
     createGoogleLocationServiceClient(); 
    } 

    private void createGoogleLocationServiceClient() { 
     googleApiClient = new GoogleApiClient.Builder(context).addApi(ActivityRecognition.API) 
       .addConnectionCallbacks(new ConnectionCallbacks() { 

        @Override 
        public void onConnectionSuspended(int arg0) { 
         Log.d(ActivityUtils.APPTAG, "GoogleApiClient Suspended"); 
        } 

        @Override 
        public void onConnected(Bundle arg0) { 
         Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connected Now"); 
         ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleApiClient, 
           ActivityUtils.DETECTION_INTERVAL_MILLISECONDS, getPendingIntent()).setResultCallback(
           new ResultCallback<Status>() { 

            @Override 
            public void onResult(Status arg0) { 
             if (arg0.isSuccess()) { 
              Log.d(ActivityUtils.APPTAG, "Updates Requested Successfully"); 
             } else { 
              Log.d(ActivityUtils.APPTAG, "Updates could not be requested"); 
             } 
            } 
           }); 
        } 
       }).addOnConnectionFailedListener(new OnConnectionFailedListener() { 
        @Override 
        public void onConnectionFailed(ConnectionResult arg0) { 
         Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Failed"); 
        } 
       }).build(); 
    } 

    public PendingIntent getRequestPendingIntent() { 
     return mActivityRecognitionPendingIntent; 
    } 

    public void setRequestPendingIntent(PendingIntent intent) { 
     mActivityRecognitionPendingIntent = intent; 
    } 

    private PendingIntent getPendingIntent() { 
     Intent intent = new Intent(context, ActivityTrackerService.class); 
     PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
     setRequestPendingIntent(pendingIntent); 
     return pendingIntent; 
    } 

    private boolean servicesConnected() { 
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context); 
     if (ConnectionResult.SUCCESS == resultCode) { 
      Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_available)); 
      return true; 
     } else { 
      Log.d(ActivityUtils.APPTAG, context.getString(R.string.play_services_unavailable)); 
      return false; 
     } 
    } 

    public void connect() { 
     if (servicesConnected() && !googleApiClient.isConnected()) { 
      Log.d(ActivityUtils.APPTAG, "GoogleApiClient Connection Initiated: connect() Called"); 
      googleApiClient.connect(); 
     } else { 
      Log.d(ActivityUtils.APPTAG, "GoogleApiClient already connected or is unavailable"); 
     } 
    } 

    public void disconnect() { 
     if (servicesConnected() && googleApiClient.isConnected()) { 
      Log.d(ActivityUtils.APPTAG, "GoogleApiClient disconnection kicked"); 
      if (mActivityRecognitionPendingIntent != null && googleApiClient != null) { 
       ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(googleApiClient, 
         mActivityRecognitionPendingIntent); 
      } 
      googleApiClient.disconnect(); 
     } else { 
      Log.d(ActivityUtils.APPTAG, "GoogleApiClient already disconnected or is unavailable"); 
     } 
    } 
} 

서비스 클래스 :

public class ActivityTrackerService extends IntentService { 

    private SharedPreferences mPrefs; 

    public ActivityTrackerService() { 
     super("ActivityTrackerService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     mPrefs = getApplicationContext().getSharedPreferences(ActivityUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE); 
     if (ActivityRecognitionResult.hasResult(intent)) { 

      ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); 
      DetectedActivity mostProbableActivity = result.getMostProbableActivity(); 
      int confidence = mostProbableActivity.getConfidence(); 
      int activityType = mostProbableActivity.getType(); 
      String activityName = ActivityUtils.getNameFromType(activityType); 

      Log.d(ActivityUtils.APPTAG, "Activity Detected:" + activityName); 

      Intent regularActivityUpdateIntent = new Intent(ActivityUtils.REGULAR_ACTIVITY_UPDATE_INTENT); 
      regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName); 
      regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType); 

      getApplicationContext().sendBroadcast(regularActivityUpdateIntent); 

      if (!mPrefs.contains(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE)) { 
       Editor editor = mPrefs.edit(); 

       editor.putInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, activityType); 
       editor.putString(ActivityUtils.KEY_PREVIOUS_ACTIVITY_NAME, activityName); 

       editor.commit(); 

       Intent newActivityUpdateIntent = new Intent(ActivityUtils.NEW_ACTIVITY_UPDATE_INTENT); 
       regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_NAME, activityName); 
       regularActivityUpdateIntent.putExtra(ActivityUtils.EXTRA_ACTIVITY_TYPE, activityType); 
       getApplicationContext().sendBroadcast(newActivityUpdateIntent); 

      } else if (isMoving(activityType) && activityChanged(activityType) && (confidence >= 50)) { 
       sendNotification(); 
      } 
     } 
    } 

    private void sendNotification() { 

     NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); 
     builder.setContentTitle("Attention").setContentText("Click to turn on GPS, or swipe to ignore") 
       .setSmallIcon(R.drawable.ic_notification).setContentIntent(getContentIntent()); 
     NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notifyManager.notify(0, builder.build()); 
    } 

    private PendingIntent getContentIntent() { 
     Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
     return PendingIntent.getActivity(getApplicationContext(), 0, gpsIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    } 

    private boolean activityChanged(int currentType) { 
     int previousType = mPrefs.getInt(ActivityUtils.KEY_PREVIOUS_ACTIVITY_TYPE, DetectedActivity.UNKNOWN); 
     if (previousType != currentType) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    private boolean isMoving(int type) { 
     switch (type) { 
     case DetectedActivity.STILL: 
     case DetectedActivity.TILTING: 
     case DetectedActivity.UNKNOWN: 
      return false; 
     default: 
      return true; 
     } 
    } 
} 

특정 안드로이드 매니페스트 항목과 같다은 다음과 같습니다

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



<service android:name=".ActivityTrackerService" > 
     </service> 

     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 

누군가가 com.google를 사용하여 노력하고 있습니다. android.gms.common.api.GoogleApiClient는 ActivityRecognition.Activit을 사용하여 ActivityUpdates를 요청합니다. yRecognitionApi.requestActivityUpdates 또는 GoogleApiClient를 사용하여 활동 업데이트를 요청할 수있는 방법이 있습니까 ??

+0

해결책을 찾았습니까? –

+0

동일한 문제, 제안 사항이 있습니까? –

+0

http://stackoverflow.com/questions/27634443/activity-recognition-using-new-googleapiclient-not-firing-activity-updates 안드로이드 매니페스트의 – samo

답변

0

나는 동일한 문제가 있었으며 명시 적 의도가 있더라도 onHandleIntent()는 호출되지 않았습니다.

그러나 onStartCommand가 호출되었으므로 의도 동작을 설정하고 확인하여 문제를 해결할 수 있습니다.

설명이나 솔루션 자체가 아니지만 적어도 실마리가 없습니다.)