Java Code Examples for com.google.android.gms.common.api.GoogleApiClient#blockingConnect()

The following examples show how to use com.google.android.gms.common.api.GoogleApiClient#blockingConnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Clears remote device notifications using the Wearable message API
 */
private void clearRemoteNotifications() {
    Log.v(TAG, ACTION_CLEAR_REMOTE_NOTIFICATIONS);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {

        // Loop through all nodes and send a clear notification message
        Iterator<String> itr = Utils.getNodes(googleApiClient).iterator();
        while (itr.hasNext()) {
            Wearable.MessageApi.sendMessage(
                    googleApiClient, itr.next(), Constants.CLEAR_NOTIFICATIONS_PATH, null);
        }
        googleApiClient.disconnect();
    }
}
 
Example 2
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Add geofences using Play Services
 */
private void addGeofencesInternal() {
    Log.v(TAG, ACTION_ADD_GEOFENCES);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, new Intent(this, UtilityReceiver.class), 0);
        GeofencingApi.addGeofences(googleApiClient,
                TouristAttractions.getGeofenceList(), pendingIntent);
        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
}
 
Example 3
Source File: QuizReportActionService.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(ACTION_RESET_QUIZ)) {
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .build();
        ConnectionResult result = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
                TimeUnit.MILLISECONDS);
        if (!result.isSuccess()) {
            Log.e(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
            return;
        }
        NodeApi.GetConnectedNodesResult nodes =
                Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
        for (Node node : nodes.getNodes()) {
            Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), RESET_QUIZ_PATH,
                    new byte[0]);
        }
    }
}
 
Example 4
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Add geofences using Play Services
 */
private void addGeofencesInternal() {
    Log.v(TAG, ACTION_ADD_GEOFENCES);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, new Intent(this, UtilityReceiver.class), 0);
        GeofencingApi.addGeofences(googleApiClient,
                TouristAttractions.getGeofenceList(), pendingIntent);
        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
}
 
Example 5
Source File: QuizReportActionService.java    From android-Quiz with Apache License 2.0 6 votes vote down vote up
@Override
public void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(ACTION_RESET_QUIZ)) {
        final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .build();
        ConnectionResult result = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
                TimeUnit.MILLISECONDS);
        if (!result.isSuccess()) {
            Log.e(TAG, "QuizReportActionService failed to connect to GoogleApiClient.");
            return;
        }

        CapabilityApi.GetCapabilityResult capabilityResult = Wearable.CapabilityApi
                .getCapability(googleApiClient, RESET_QUIZ_CAPABILITY_NAME,
                        CapabilityApi.FILTER_REACHABLE)
                .await(GET_CAPABILITIES_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        if (capabilityResult.getStatus().isSuccess()) {
            sendResetMessage(googleApiClient, capabilityResult.getCapability());
        } else {
            Log.e(TAG, "Failed to get capabilities, status: "
                    + capabilityResult.getStatus().getStatusMessage());
        }
    }
}
 
Example 6
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the actual message to ask other devices that are capable of showing "details" to start
 * the appropriate activity
 *
 * @param path the path to pass to the wearable message API
 * @param extraInfo extra info that varies based on the path being sent
 */
private void startDeviceActivityInternal(String path, String extraInfo) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        CapabilityApi.GetCapabilityResult result = Wearable.CapabilityApi.getCapability(
                googleApiClient,
                getApplicationContext().getString(R.string.show_detail_capability_name),
                CapabilityApi.FILTER_REACHABLE)
                .await(GET_CAPABILITY_TIMEOUT_S, TimeUnit.SECONDS);
        if (result.getStatus().isSuccess()) {
            Set<Node> nodes = result.getCapability().getNodes();
            for (Node node : nodes) {
                Wearable.MessageApi.sendMessage(
                        googleApiClient, node.getId(), path, extraInfo.getBytes());
            }
        } else {
            Log.e(TAG, "startDeviceActivityInternal() Failed to get capabilities, status: "
                    + result.getStatus().getStatusMessage());
        }

        googleApiClient.disconnect();
    }
}
 
Example 7
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the actual message to ask other devices that are capable of showing "details" to start
 * the appropriate activity
 *
 * @param path the path to pass to the wearable message API
 * @param extraInfo extra info that varies based on the path being sent
 */
private void startDeviceActivityInternal(String path, String extraInfo) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {
        CapabilityApi.GetCapabilityResult result = Wearable.CapabilityApi.getCapability(
                googleApiClient,
                getApplicationContext().getString(R.string.show_detail_capability_name),
                CapabilityApi.FILTER_REACHABLE)
                .await(GET_CAPABILITY_TIMEOUT_S, TimeUnit.SECONDS);
        if (result.getStatus().isSuccess()) {
            Set<Node> nodes = result.getCapability().getNodes();
            for (Node node : nodes) {
                Wearable.MessageApi.sendMessage(
                        googleApiClient, node.getId(), path, extraInfo.getBytes());
            }
        } else {
            Log.e(TAG, "startDeviceActivityInternal() Failed to get capabilities, status: "
                    + result.getStatus().getStatusMessage());
        }

        googleApiClient.disconnect();
    }
}
 
Example 8
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a location update is requested
 */
private void requestLocationInternal() {
    Log.v(TAG, ACTION_REQUEST_LOCATION);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {

        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);

        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(
                    FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }

        // Request new location
        LocationRequest mLocationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(
                googleApiClient, mLocationRequest,
                PendingIntent.getService(this, 0, locationUpdatedIntent, 0));

        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
}
 
Example 9
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a location update is requested
 */
private void requestLocationInternal() {
    Log.v(TAG, ACTION_REQUEST_LOCATION);
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {

        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);

        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(
                    FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }

        // Request new location
        LocationRequest mLocationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(
                googleApiClient, mLocationRequest,
                PendingIntent.getService(this, 0, locationUpdatedIntent, 0));

        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
}
 
Example 10
Source File: WearService.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
public void run() {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e("ETSMobile-Wear", connectionResult.getErrorMessage());
        return;
    }

    PutDataMapRequest dataMapReq = PutDataMapRequest.create(path);

    ArrayList<DataMap> dataMapArrayList = new ArrayList<>();
    for (Seances seance : seances) {
        dataMapArrayList.add(seance.putData());
    }
    dataMapReq.getDataMap().putDataMapArrayList("list_seances", dataMapArrayList);

    PutDataRequest request = dataMapReq.asPutDataRequest();

    DataApi.DataItemResult dataItemResult = Wearable
            .DataApi
            .putDataItem(googleApiClient, request)
            .await();

    if (dataItemResult.getStatus().isSuccess()) {
        if (BuildConfig.DEBUG) Log.d("SendToDataLayerThread", "Data sent successfully!!");
    } else {
        // Log an error
        if (BuildConfig.DEBUG)
            Log.d("SendToDataLayerThread", "ERROR: failed to send Message");
    }
}
 
Example 11
Source File: MainActivity.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e("ETSMobile-Wear", connectionResult.getErrorMessage());
        return null;
    }

    MessageApi.SendMessageResult result =
            Wearable.MessageApi.sendMessage(
                    googleApiClient,
                    Utils.getRemoteNodeId(googleApiClient),
                    "/today_req",
                    null)
                    .await();

    if (result.getStatus().isSuccess()) {
        Log.d("wearThread", "SUCCESS : Message sent");
    } else {
        Log.d("wearThread", "ERROR: failed to send Message");
    }

    return null;

}
 
Example 12
Source File: RegistrationIntentService.java    From friendlyping with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the registration to the server.
 *
 * @param token The token to send.
 * @throws IOException Thrown when a connection issue occurs.
 */
private void sendRegistrationToServer(String token) throws IOException {
    final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_PROFILE)
            .build();
    googleApiClient.blockingConnect();

    Bundle registration = createRegistrationBundle(googleApiClient);
    registration.putString(PingerKeys.REGISTRATION_TOKEN, token);

    // Register the user at the server.
    GoogleCloudMessaging.getInstance(this).send(FriendlyPingUtil.getServerUrl(this),
            String.valueOf(System.currentTimeMillis()), registration);
}
 
Example 13
Source File: FusedLocationModule.java    From react-native-fused-location with MIT License 4 votes vote down vote up
@SuppressWarnings("All")
@ReactMethod
public void getFusedLocation(boolean forceNewLocation, final Promise promise) {
    try {
        if (!areProvidersAvailable()) {
            promise.reject(TAG, ERROR_NO_LOCATION_PROVIDER);
            return;
        }
        if (!checkForPlayServices()) {
            promise.reject(TAG, ERROR_PLAY_SERVICES_NOT_FOUND);
            return;
        }
        if (ActivityCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            promise.reject(TAG, ERROR_UNAUTHORIZED);
            return;
        }
        final GoogleApiClient googleApiClient;
        LocationRequest request = buildLR();
        googleApiClient = new GoogleApiClient.Builder(getReactApplicationContext())
                .addApi(LocationServices.API)
                .build();
        googleApiClient.blockingConnect();
        final Location location;
        if (!forceNewLocation) {
            location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        } else {
            location = null;
        }
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    super.onLocationResult(locationResult);
                    promise.resolve(convertLocationToJSON(locationResult.getLastLocation()));
                }

                @Override
                public void onLocationAvailability(LocationAvailability locationAvailability) {
                    super.onLocationAvailability(locationAvailability);
                    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
                    googleApiClient.disconnect();
                    if (!locationAvailability.isLocationAvailable()) {
                        promise.reject(TAG, "Location not available. Does your phone have GPS turned on and internet connectivity?");
                    }
                }
            }, null);
            return;
        }
        promise.resolve(convertLocationToJSON(location));
        googleApiClient.disconnect();
    } catch (Exception ex) {
        Log.e(TAG, "Native Location Module ERR - " + ex.toString());
        promise.reject(TAG, ex.toString());
    }
}
 
Example 14
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 * @param attractions list of attraction data to transfer over
 */
private void sendDataToWearable(List<Attraction> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    // Limit attractions to send
    int count = attractions.size() > Constants.MAX_ATTRACTIONS ?
            Constants.MAX_ATTRACTIONS : attractions.size();

    ArrayList<DataMap> attractionsData = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
        Attraction attraction = attractions.get(i);

        Bitmap image = null;
        Bitmap secondaryImage = null;

        try {
            // Fetch and resize attraction image bitmap
            image = Glide.with(this)
                    .load(attraction.imageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();

            secondaryImage = Glide.with(this)
                    .load(attraction.secondaryImageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();
        } catch (InterruptedException | ExecutionException e) {
            Log.e(TAG, "Exception loading bitmap from network");
        }

        if (image != null && secondaryImage != null) {

            DataMap attractionData = new DataMap();

            String distance = Utils.formatDistanceBetween(
                    Utils.getLocation(this), attraction.location);

            attractionData.putString(Constants.EXTRA_TITLE, attraction.name);
            attractionData.putString(Constants.EXTRA_DESCRIPTION, attraction.description);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LAT, attraction.location.latitude);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LNG, attraction.location.longitude);
            attractionData.putString(Constants.EXTRA_DISTANCE, distance);
            attractionData.putString(Constants.EXTRA_CITY, attraction.city);
            attractionData.putAsset(Constants.EXTRA_IMAGE,
                    Utils.createAssetFromBitmap(image));
            attractionData.putAsset(Constants.EXTRA_IMAGE_SECONDARY,
                    Utils.createAssetFromBitmap(secondaryImage));

            attractionsData.add(attractionData);
        }
    }

    if (connectionResult.isSuccess() && googleApiClient.isConnected()
            && attractionsData.size() > 0) {

        PutDataMapRequest dataMap = PutDataMapRequest.create(Constants.ATTRACTION_PATH);
        dataMap.getDataMap().putDataMapArrayList(Constants.EXTRA_ATTRACTIONS, attractionsData);
        dataMap.getDataMap().putLong(Constants.EXTRA_TIMESTAMP, new Date().getTime());
        PutDataRequest request = dataMap.asPutDataRequest();
        request.setUrgent();

        // Send the data over
        DataApi.DataItemResult result =
                Wearable.DataApi.putDataItem(googleApiClient, request).await();

        if (!result.getStatus().isSuccess()) {
            Log.e(TAG, String.format("Error sending data using DataApi (error code = %d)",
                    result.getStatus().getStatusCode()));
        }

    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
    googleApiClient.disconnect();
}
 
Example 15
Source File: AttractionsActivity.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
@Override
protected ArrayList<Attraction> doInBackground(Uri... params) {
    mAttractions.clear();

    // Connect to Play Services and the Wearable API
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
        return null;
    }

    Uri attractionsUri = params[0];
    DataApi.DataItemResult dataItemResult =
            Wearable.DataApi.getDataItem(googleApiClient, attractionsUri).await();

    if (dataItemResult.getStatus().isSuccess() && dataItemResult.getDataItem() != null) {
        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItemResult.getDataItem());
        List<DataMap> attractionsData =
                dataMapItem.getDataMap().getDataMapArrayList(Constants.EXTRA_ATTRACTIONS);

        // Loop through each attraction, adding them to the list
        Iterator<DataMap> itr = attractionsData.iterator();
        while (itr.hasNext()) {
            DataMap attractionData = itr.next();

            Attraction attraction = new Attraction();
            attraction.name = attractionData.getString(Constants.EXTRA_TITLE);
            attraction.description =
                    attractionData.getString(Constants.EXTRA_DESCRIPTION);
            attraction.city = attractionData.get(Constants.EXTRA_CITY);
            attraction.distance =
                    attractionData.getString(Constants.EXTRA_DISTANCE);
            attraction.location = new LatLng(
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LAT),
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LNG));
            attraction.image = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE));
            attraction.secondaryImage = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE_SECONDARY));

            mAttractions.add(attraction);
        }
    }

    googleApiClient.disconnect();

    return mAttractions;
}
 
Example 16
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Called when a location update is requested
 */
private void requestLocationInternal() {
    Log.v(TAG, ACTION_REQUEST_LOCATION);

    if (!Utils.checkFineLocationPermission(this)) {
        return;
    }

    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (connectionResult.isSuccess() && googleApiClient.isConnected()) {

        Intent locationUpdatedIntent = new Intent(this, UtilityService.class);
        locationUpdatedIntent.setAction(ACTION_LOCATION_UPDATED);

        // Send last known location out first if available
        Location location = FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            Intent lastLocationIntent = new Intent(locationUpdatedIntent);
            lastLocationIntent.putExtra(
                    FusedLocationProviderApi.KEY_LOCATION_CHANGED, location);
            startService(lastLocationIntent);
        }

        // Request new location
        LocationRequest mLocationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        FusedLocationApi.requestLocationUpdates(
                googleApiClient, mLocationRequest,
                PendingIntent.getService(this, 0, locationUpdatedIntent, 0));

        googleApiClient.disconnect();
    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
}
 
Example 17
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 * @param attractions list of attraction data to transfer over
 */
private void sendDataToWearable(List<Attraction> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    // Limit attractions to send
    int count = attractions.size() > Constants.MAX_ATTRACTIONS ?
            Constants.MAX_ATTRACTIONS : attractions.size();

    ArrayList<DataMap> attractionsData = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
        Attraction attraction = attractions.get(i);

        Bitmap image = null;
        Bitmap secondaryImage = null;

        try {
            // Fetch and resize attraction image bitmap
            image = Glide.with(this)
                    .load(attraction.imageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();

            secondaryImage = Glide.with(this)
                    .load(attraction.secondaryImageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();
        } catch (InterruptedException | ExecutionException e) {
            Log.e(TAG, "Exception loading bitmap from network");
        }

        if (image != null && secondaryImage != null) {

            DataMap attractionData = new DataMap();

            String distance = Utils.formatDistanceBetween(
                    Utils.getLocation(this), attraction.location);

            attractionData.putString(Constants.EXTRA_TITLE, attraction.name);
            attractionData.putString(Constants.EXTRA_DESCRIPTION, attraction.description);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LAT, attraction.location.latitude);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LNG, attraction.location.longitude);
            attractionData.putString(Constants.EXTRA_DISTANCE, distance);
            attractionData.putString(Constants.EXTRA_CITY, attraction.city);
            attractionData.putAsset(Constants.EXTRA_IMAGE,
                    Utils.createAssetFromBitmap(image));
            attractionData.putAsset(Constants.EXTRA_IMAGE_SECONDARY,
                    Utils.createAssetFromBitmap(secondaryImage));

            attractionsData.add(attractionData);
        }
    }

    if (connectionResult.isSuccess() && googleApiClient.isConnected()
            && attractionsData.size() > 0) {

        PutDataMapRequest dataMap = PutDataMapRequest.create(Constants.ATTRACTION_PATH);
        dataMap.getDataMap().putDataMapArrayList(Constants.EXTRA_ATTRACTIONS, attractionsData);
        dataMap.getDataMap().putLong(Constants.EXTRA_TIMESTAMP, new Date().getTime());
        PutDataRequest request = dataMap.asPutDataRequest();

        // Send the data over
        DataApi.DataItemResult result =
                Wearable.DataApi.putDataItem(googleApiClient, request).await();

        if (!result.getStatus().isSuccess()) {
            Log.e(TAG, String.format("Error sending data using DataApi (error code = %d)",
                    result.getStatus().getStatusCode()));
        }

    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
    googleApiClient.disconnect();
}
 
Example 18
Source File: AttractionsActivity.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected ArrayList<Attraction> doInBackground(Uri... params) {
    mAttractions.clear();

    // Connect to Play Services and the Wearable API
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
        return null;
    }

    Uri attractionsUri = params[0];
    DataApi.DataItemResult dataItemResult =
            Wearable.DataApi.getDataItem(googleApiClient, attractionsUri).await();

    if (dataItemResult.getStatus().isSuccess() && dataItemResult.getDataItem() != null) {
        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItemResult.getDataItem());
        List<DataMap> attractionsData =
                dataMapItem.getDataMap().getDataMapArrayList(Constants.EXTRA_ATTRACTIONS);

        // Loop through each attraction, adding them to the list
        Iterator<DataMap> itr = attractionsData.iterator();
        while (itr.hasNext()) {
            DataMap attractionData = itr.next();

            Attraction attraction = new Attraction();
            attraction.name = attractionData.getString(Constants.EXTRA_TITLE);
            attraction.description =
                    attractionData.getString(Constants.EXTRA_DESCRIPTION);
            attraction.city = attractionData.get(Constants.EXTRA_CITY);
            attraction.distance =
                    attractionData.getString(Constants.EXTRA_DISTANCE);
            attraction.location = new LatLng(
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LAT),
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LNG));
            attraction.image = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE));
            attraction.secondaryImage = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE_SECONDARY));

            mAttractions.add(attraction);
        }
    }

    googleApiClient.disconnect();

    return mAttractions;
}
 
Example 19
Source File: ListenerService.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
private void showNotification(Uri attractionsUri, ArrayList<DataMap> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
        return;
    }

    Intent intent = new Intent(this, AttractionsActivity.class);
    // Pass through the data Uri as an extra
    intent.putExtra(Constants.EXTRA_ATTRACTIONS_URI, attractionsUri);
    PendingIntent pendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    int count = attractions.size();

    DataMap attraction = attractions.get(0);

    Bitmap bitmap = Utils.loadBitmapFromAsset(
            googleApiClient, attraction.getAsset(Constants.EXTRA_IMAGE));

    PendingIntent deletePendingIntent = PendingIntent.getService(
            this, 0, UtilityService.getClearRemoteNotificationsIntent(this), 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentText(getResources().getQuantityString(
                    R.plurals.attractions_found, count, count))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setDeleteIntent(deletePendingIntent)
            .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_full_explore,
                    getString(R.string.action_explore),
                    pendingIntent).build())
            .extend(new NotificationCompat.WearableExtender()
                    .setBackground(bitmap)
            )
            .build();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(Constants.WEAR_NOTIFICATION_ID, notification);

    googleApiClient.disconnect();
}
 
Example 20
Source File: ListenerService.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
private void showNotification(Uri attractionsUri, ArrayList<DataMap> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
        return;
    }

    Intent intent = new Intent(this, AttractionsActivity.class);
    // Pass through the data Uri as an extra
    intent.putExtra(Constants.EXTRA_ATTRACTIONS_URI, attractionsUri);
    PendingIntent pendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    int count = attractions.size();

    DataMap attraction = attractions.get(0);

    Bitmap bitmap = Utils.loadBitmapFromAsset(
            googleApiClient, attraction.getAsset(Constants.EXTRA_IMAGE));

    PendingIntent deletePendingIntent = PendingIntent.getService(
            this, 0, UtilityService.getClearRemoteNotificationsIntent(this), 0);

    Notification notification = new Notification.Builder(this)
            .setContentText(getResources().getQuantityString(
                    R.plurals.attractions_found, count, count))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setDeleteIntent(deletePendingIntent)
            .addAction(R.drawable.ic_full_explore,
                    getString(R.string.action_explore),
                    pendingIntent)
            .extend(new Notification.WearableExtender()
                    .setBackground(bitmap)
            )
            .build();

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(Constants.WEAR_NOTIFICATION_ID, notification);

    googleApiClient.disconnect();
}