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

The following examples show how to use com.google.android.gms.common.api.GoogleApiClient#disconnect() . 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
/**
 * Trigger a message to ask other devices to clear their notifications
 */
private void clearRemoteNotificationsInternal() {
    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()) {
        Iterator<String> itr = Utils.getNodes(googleApiClient).iterator();
        while (itr.hasNext()) {
            // Loop through all connected nodes
            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: 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 4
Source File: UtilityService.java    From wear-os-samples 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 5
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 6
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 7
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 8
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Add geofences using Play Services
 */
private void addGeofencesInternal() {
    Log.v(TAG, ACTION_ADD_GEOFENCES);

    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()) {
        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 9
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 10
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 11
Source File: GoogleApiClientBridge.java    From friendspell with Apache License 2.0 4 votes vote down vote up
public void disconnect(String token) {
  GoogleApiClient googleApiClient = clients.get(token);
  if (googleApiClient.isConnected()) {
    googleApiClient.disconnect();
  }
}
 
Example 12
Source File: QuizListenerService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

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

    ConnectionResult connectionResult = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
            TimeUnit.MILLISECONDS);
    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
        return;
    }

    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            DataItem dataItem = event.getDataItem();
            DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
            if (dataMap.getBoolean(QUESTION_WAS_ANSWERED)
                    || dataMap.getBoolean(QUESTION_WAS_DELETED)) {
                // Ignore the change in data; it is used in MainActivity to update
                // the question's status (i.e. was the answer right or wrong or left blank).
                continue;
            }
            String question = dataMap.getString(QUESTION);
            int questionIndex = dataMap.getInt(QUESTION_INDEX);
            int questionNum = questionIndex + 1;
            String[] answers = dataMap.getStringArray(ANSWERS);
            int correctAnswerIndex = dataMap.getInt(CORRECT_ANSWER_INDEX);
            Intent deleteOperation = new Intent(this, DeleteQuestionService.class);
            deleteOperation.setData(dataItem.getUri());
            PendingIntent deleteIntent = PendingIntent.getService(this, 0,
                    deleteOperation, PendingIntent.FLAG_UPDATE_CURRENT);
            // First page of notification contains question as Big Text.
            Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle()
                    .setBigContentTitle(getString(R.string.question, questionNum))
                    .bigText(question);
            Notification.Builder builder = new Notification.Builder(this)
                    .setStyle(bigTextStyle)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setLocalOnly(true)
                    .setDeleteIntent(deleteIntent);

            // Add answers as actions.
            Notification.WearableExtender wearableOptions = new Notification.WearableExtender();
            for (int i = 0; i < answers.length; i++) {
                Notification answerPage = new Notification.Builder(this)
                        .setContentTitle(question)
                        .setContentText(answers[i])
                        .extend(new Notification.WearableExtender()
                                .setContentAction(i))
                        .build();

                boolean correct = (i == correctAnswerIndex);
                Intent updateOperation = new Intent(this, UpdateQuestionService.class);
                // Give each intent a unique action.
                updateOperation.setAction("question_" + questionIndex + "_answer_" + i);
                updateOperation.setData(dataItem.getUri());
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_INDEX,
                        questionIndex);
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
                PendingIntent updateIntent = PendingIntent.getService(this, 0, updateOperation,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                Notification.Action action = new Notification.Action.Builder(
                        questionNumToDrawableId.get(i), null, updateIntent)
                        .build();
                wearableOptions.addAction(action).addPage(answerPage);
            }
            builder.extend(wearableOptions);
            Notification notification = builder.build();
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .notify(questionIndex, notification);
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            Uri uri = event.getDataItem().getUri();
            // URI's are of the form "/question/0", "/question/1" etc.
            // We use the question index as the notification id.
            int notificationId = Integer.parseInt(uri.getLastPathSegment());
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .cancel(notificationId);
        }
        // Delete the quiz report, if it exists.
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .cancel(QUIZ_REPORT_NOTIF_ID);
    }
    googleApiClient.disconnect();
}
 
Example 13
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 14
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();
}
 
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: 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 17
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 18
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 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: 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();
}