수색…


비고

Fence API 가 지정된 상태를 계속 확인하는 동안 Snapshot API 는 현재 상태를 요청하는 데 사용되며 앱이 실행되지 않을 때 콜백을 전송합니다.

전반적으로 Snapshot API 또는 Fence API를 사용하기위한 몇 가지 기본 단계가 있습니다.

  • Google Developers Console 에서 API 키 가져 오기

  • 매니페스트에 필요한 권한 및 API 키를 추가합니다.

     <!-- Not required for getting current headphone state -->
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
     <!-- Only required for actvity recognition -->
     <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
    
     <!-- Replace with your actual API key from console -->
     <meta-data android:name="com.google.android.awareness.API_KEY"
                android:value="YOUR_API_KEY"/>
    
     <!-- Required for Snapshot API only -->
     <meta-data android:name="com.google.android.geo.API_KEY"
                android:value="YOUR_API_KEY"/> 
    
  • 가능하면 활동의 onCreate () 메소드에서 GoogleApiClient 어딘가에 초기화하십시오.

     GoogleApiClient client = new GoogleApiClient.Builder(context)
         .addApi(Awareness.API)
         .build();
     client.connect();
    
  • 원하는 API를 호출하십시오.

  • 구문 분석 결과

필요한 사용자 권한을 확인하는 쉬운 방법은 다음과 같은 방법입니다.

private boolean isFineLocationGranted() {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
        Log.e(getClass().getSimpleName(), "Fine location permission not granted!");
    }
}

Snapshot API를 사용하여 현재 사용자 활동 가져 오기

사용자의 신체 활동에 대한 일시적이지 않은 요청의 경우 Snapshot API를 사용하십시오.

// Remember to initialize your client as described in the Remarks section
Awareness.SnapshotApi.getDetectedActivity(client)
    .setResultCallback(new ResultCallback<DetectedActivityResult>() {
        @Override
        public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
            if (!detectedActivityResult.getStatus().isSuccess()) {
                Log.e(getClass().getSimpleName(), "Could not get the current activity.");
                return;
            }
            ActivityRecognitionResult result = detectedActivityResult
                .getActivityRecognitionResult();
            DetectedActivity probableActivity = result.getMostProbableActivity();
            Log.i(getClass().getSimpleName(), "Activity received : " + 
                probableActivity.toString());
        }
    });

Snapshot API로 헤드폰 상태 가져 오기

// Remember to initialize your client as described in the Remarks section
Awareness.SnapshotApi.getHeadphoneState(client)
    .setResultCallback(new ResultCallback<HeadphoneStateResult>() {
        @Override
        public void onResult(@NonNull HeadphoneStateResult headphoneStateResult) {
            Log.i(TAG, "Headphone state connection state: " + 
                headphoneStateResult.getHeadphoneState()
                .getState() == HeadphoneState.PLUGGED_IN));
        }
    });

Snapshot API를 사용하여 현재 위치 가져 오기

// Remember to intialize your client as described in the Remarks section
Awareness.SnapshotApi.getLocation(client)
    .setResultCallback(new ResultCallback<LocationResult>() {
        @Override
        public void onResult(@NonNull LocationResult locationResult) {
            Location location = locationResult.getLocation();
            Log.i(getClass().getSimpleName(), "Coordinates: "location.getLatitude() + "," + 
                location.getLongitude() + ", radius : " + location.getAccuracy());
        }
    });

Snapshot API를 사용하여 주변 장소 가져 오기

// Remember to initialize your client as described in the Remarks section 
Awareness.SnapshotApi.getPlaces(client)
    .setResultCallback(new ResultCallback<PlacesResult>() {
        @Override
        public void onResult(@NonNull PlacesResult placesResult) {
            List<PlaceLikelihood> likelihoodList = placesResult.getPlaceLikelihoods();
            if (likelihoodList == null || likelihoodList.isEmpty()) {
                Log.e(getClass().getSimpleName(), "No likely places");
            }
        }
    });

해당 위치에서 데이터를 가져 오는 방법은 다음과 같습니다.

Place place = placeLikelihood.getPlace();
String likelihood = placeLikelihood.getLikelihood();
Place place = likelihood.getPlace();
String placeName = place.getName();
String placeAddress = place.getAddress();
String placeCoords = place.getLatLng();
String locale = extractFromLocale(place.getLocale()));

Snapshot API를 사용하여 현재 날씨 가져 오기

// Remember to initialize your client as described in the Remarks section
Awareness.SnapshotApi.getWeather(client)
    .setResultCallback(new ResultCallback<WeatherResult>() {
        @Override
        public void onResult(@NonNull WeatherResult weatherResult) {
            Weather weather = weatherResult.getWeather();
            if (weather == null) {
                Log.e(getClass().getSimpleName(), "No weather received");
            } else {
                Log.i(getClass().getSimpleName(), "Temperature is " +
                        weather.getTemperature(Weather.CELSIUS) + ", feels like " +
                        weather.getFeelsLikeTemperature(Weather.CELSIUS) + 
                        ", humidity is " + weather.getHumidity());
            }
        }
    });

Fence API를 사용하여 사용자 활동 변경

사용자가 걷기, 실행 또는 DetectedActivityFence 클래스의 다른 활동과 같은 활동을 시작하거나 완료 할 때를 감지하려면 탐지하려는 활동에 대한 울타리 를 만들고 사용자가 시작 / 이 작업을 완료합니다. BroadcastReceiver 를 사용하면 활동이 포함 된 데이터로 인 Intent 를 얻을 수 있습니다.

// Your own action filter, like the ones used in the Manifest.
private static final String FENCE_RECEIVER_ACTION = BuildConfig.APPLICATION_ID +
    "FENCE_RECEIVER_ACTION";
private static final String FENCE_KEY = "walkingFenceKey";
private FenceReceiver mFenceReceiver;
private PendingIntent mPendingIntent;

// Make sure to initialize your client as described in the Remarks section.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // etc.

    // The 0 is a standard Activity request code that can be changed to your needs.
    mPendingIntent = PendingIntent.getBroadcast(this, 0, 
        new Intent(FENCE_RECEIVER_ACTION), 0);
    registerReceiver(mFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));

    // Create the fence.
    AwarenessFence fence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
    // Register the fence to receive callbacks.
    Awareness.FenceApi.updateFences(client, new FenceUpdateRequest.Builder()
        .addFence(FENCE_KEY, fence, mPendingIntent)
        .build())
        .setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                if (status.isSuccess()) {
                    Log.i(FENCE_KEY, "Successfully registered.");
                } else {
                    Log.e(FENCE_KEY, "Could not be registered: " + status);
                }
            }
        });
    }
}

이제 사용자가 Activity를 변경할 때 콜백을 받기 위해 BroadcastReceiver 로 인 텐트를 수신 할 수 있습니다.

public class FenceReceiver extends BroadcastReceiver {

    private static final String TAG = "FenceReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        // Get the fence state
        FenceState fenceState = FenceState.extract(intent);

        switch (fenceState.getCurrentState()) {
            case FenceState.TRUE:
                Log.i(TAG, "User is walking");
                break;
            case FenceState.FALSE:
                Log.i(TAG, "User is not walking");
                break;
            case FenceState.UNKNOWN:
                Log.i(TAG, "User is doing something unknown");
                break;
        }
    }
}

Fence API를 사용하여 특정 범위 내의 위치를 ​​변경합니다.

사용자가 특정 위치를 입력 할 때를 감지하려면 사용자가 원하는 위치로 들어가거나 이동할 때 원하는 반지름으로 특정 위치에 울타리를 만들 수 있습니다.

// Your own action filter, like the ones used in the Manifest
private static final String FENCE_RECEIVER_ACTION = BuildConfig.APPLICATION_ID +
    "FENCE_RECEIVER_ACTION";
private static final String FENCE_KEY = "locationFenceKey";
private FenceReceiver mFenceReceiver;
private PendingIntent mPendingIntent;

// Make sure to initialize your client as described in the Remarks section
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // etc

    // The 0 is a standard Activity request code that can be changed for your needs
    mPendingIntent = PendingIntent.getBroadcast(this, 0, 
        new Intent(FENCE_RECEIVER_ACTION), 0);
    registerReceiver(mFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));

    // Create the fence
    AwarenessFence fence = LocationFence.entering(48.136334, 11.581660, 25);
    // Register the fence to receive callbacks.
    Awareness.FenceApi.updateFences(client, new FenceUpdateRequest.Builder()
        .addFence(FENCE_KEY, fence, mPendingIntent)
        .build())
        .setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                if (status.isSuccess()) {
                    Log.i(FENCE_KEY, "Successfully registered.");
                } else {
                    Log.e(FENCE_KEY, "Could not be registered: " + status);
                }
            }
        });
    }
}

이제 BroadcastReciver를 만들어 사용자 상태의 업데이트를 받아들입니다.

public class FenceReceiver extends BroadcastReceiver {

    private static final String TAG = "FenceReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        // Get the fence state
        FenceState fenceState = FenceState.extract(intent);

        switch (fenceState.getCurrentState()) {
            case FenceState.TRUE:
                Log.i(TAG, "User is in location");
                break;
            case FenceState.FALSE:
                Log.i(TAG, "User is not in location");
                break;
            case FenceState.UNKNOWN:
                Log.i(TAG, "User is doing something unknown");
                break;
        }
    }
}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow