Android
Googles medvetenhets-API: er
Sök…
Anmärkningar
Kom ihåg att Snapshot API används för att begära aktuellt tillstånd medan Fence API kontinuerligt letar efter ett specificerat tillstånd och skickar återuppringningar när en app inte körs.
Totalt sett finns det några grundläggande steg för att använda Snapshot API eller Fence API:
Skaffa en API-nyckel från Google Developers Console
Lägg till nödvändiga behörigheter och API-nyckel till manifestet:
<!-- 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"/>
Initalisera
GoogleApiClient
någonstans, helst i din aktivitets onCreate () -metod.GoogleApiClient client = new GoogleApiClient.Builder(context) .addApi(Awareness.API) .build(); client.connect();
Ring API som du väljer
Analysresultat
Ett enkelt sätt att kontrollera om det krävs användarrättigheter är en metod som denna:
private boolean isFineLocationGranted() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getSimpleName(), "Fine location permission not granted!");
}
}
Få aktuell användaraktivitet med hjälp av Snapshot API
Använd Snapshot-API: en för en gång, icke-konstant begäran om en användares fysiska aktivitet:
// 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());
}
});
Få hörlurar med 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));
}
});
Få aktuell plats med 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());
}
});
Få platser i närheten med 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");
}
}
});
När det gäller att få informationen på dessa platser, här är några alternativ:
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()));
Få aktuellt väder med 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());
}
}
});
Få ändringar i användaraktivitet med Fence API
Om du vill upptäcka när din användare startar eller avslutar en aktivitet som att gå, springa eller någon annan aktivitet i klassen DetectedActivityFence
, kan du skapa ett staket för den aktivitet som du vill upptäcka och bli meddelad när din användare startar / avslutar den här aktiviteten. Genom att använda en BroadcastReceiver
får du ett Intent
med data som innehåller aktiviteten:
// 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);
}
}
});
}
}
Nu kan du få avsikten med en BroadcastReceiver
att få återuppringningar när användaren ändrar aktiviteten:
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;
}
}
}
Få ändringar för plats inom ett visst intervall med hjälp av Fence API
Om du vill upptäcka när din användare anger en specifik plats kan du skapa ett staket för den specifika platsen med en radie du vill och bli meddelad när din användare kommer in eller lämnar platsen.
// 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);
}
}
});
}
}
Skapa nu en BroadcastReciver för att få uppdateringar i användarläge:
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;
}
}
}