Android
API de conocimiento de Google
Buscar..
Observaciones
Recuerde, la API de instantáneas se utiliza para solicitar el estado actual, mientras que la API de cercado comprueba continuamente un estado específico y envía devoluciones de llamada cuando una aplicación no se está ejecutando.
En general, hay algunos pasos básicos para utilizar la API de instantáneas o la API de Fence:
Obtenga una clave API de la Consola de Desarrolladores de Google
Agregue los permisos necesarios y la clave API al manifiesto:
<!-- 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"/>
Inicialice el
GoogleApiClient
algún lugar, preferiblemente en el método onCreate () de su actividad.GoogleApiClient client = new GoogleApiClient.Builder(context) .addApi(Awareness.API) .build(); client.connect();
Llame a la API de su elección
Parse el resultado
Una forma fácil de verificar el permiso de usuario necesario es un método como este:
private boolean isFineLocationGranted() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(getClass().getSimpleName(), "Fine location permission not granted!");
}
}
Obtenga la actividad actual del usuario utilizando la API de instantáneas
Para solicitudes no constantes de una sola vez para la actividad física de un usuario, use la API de instantáneas:
// 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());
}
});
Obtener el estado de los auriculares con la API de instantáneas
// 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));
}
});
Obtener ubicación actual utilizando API de instantáneas
// 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());
}
});
Obtener lugares cercanos utilizando API de instantáneas
// 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");
}
}
});
En cuanto a obtener los datos en esos lugares, aquí hay algunas opciones:
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()));
Obtener el clima actual utilizando API de instantáneas
// 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());
}
}
});
Obtén cambios en la actividad del usuario con Fence API
Si desea detectar cuándo su usuario comienza o finaliza una actividad como caminar, correr o cualquier otra actividad de la clase DetectedActivityFence
, puede crear una cerca para la actividad que desea detectar y recibir una notificación cuando su usuario comience / Termina esta actividad. Al utilizar un BroadcastReceiver
, obtendrá un Intent
con datos que contienen la actividad:
// 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);
}
}
});
}
}
Ahora puede recibir la intención con un BroadcastReceiver
para obtener devoluciones de llamada cuando el usuario cambia la actividad:
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;
}
}
}
Obtenga cambios para la ubicación dentro de un cierto rango usando la API de Fence
Si desea detectar cuándo su usuario ingresa a una ubicación específica, puede crear una cerca para la ubicación específica con el radio que desee y recibir una notificación cuando su usuario ingrese o salga de la ubicación.
// 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);
}
}
});
}
}
Ahora cree un BroadcastReciver para recibir actualizaciones en el estado del usuario:
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;
}
}
}