Java Code Examples for com.google.android.gms.common.ConnectionResult#isSuccess()

The following examples show how to use com.google.android.gms.common.ConnectionResult#isSuccess() . 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 wear-os-samples 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
/**
 * 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 3
Source File: WearableApis.java    From courier with Apache License 2.0 6 votes vote down vote up
/** For use by generated code, do not use */
static void ensureApiClient(final Context context) {
    if(googleApiClient!=null && googleApiClient.isConnected()) {
        return;
    }
    if(WearableApis.hasAllMockApis()) {
        return;
    }

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

    final ConnectionResult result = googleApiClient.blockingConnect();

    if(!result.isSuccess()) {
        googleApiClient = null;
    }
}
 
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 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 6
Source File: RemoteSensorManager.java    From SensorDashboard with Apache License 2.0 5 votes vote down vote up
private boolean validateConnection() {
    if (googleApiClient.isConnected()) {
        return true;
    }

    ConnectionResult result = googleApiClient.blockingConnect(CLIENT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);

    return result.isSuccess();
}
 
Example 7
Source File: ChromeGoogleApiClientImpl.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public boolean connectWithTimeout(long timeout) {
    TraceEvent.begin("ChromeGoogleApiClientImpl:connectWithTimeout");
    try {
        ConnectionResult result = mClient.blockingConnect(timeout, TimeUnit.MILLISECONDS);
        if (!result.isSuccess()) {
            Log.e(TAG, "Connection to GmsCore unsuccessful. Error %d", result.getErrorCode());
        } else {
            Log.d(TAG, "Connection to GmsCore successful.");
        }
        return result.isSuccess();
    } finally {
        TraceEvent.end("ChromeGoogleApiClientImpl:connectWithTimeout");
    }
}
 
Example 8
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 9
Source File: ChromeGoogleApiClientImpl.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public boolean connectWithTimeout(long timeout) {
    TraceEvent.begin("ChromeGoogleApiClientImpl:connectWithTimeout");
    try {
        ConnectionResult result = mClient.blockingConnect(timeout, TimeUnit.MILLISECONDS);
        if (!result.isSuccess()) {
            Log.e(TAG, "Connection to GmsCore unsuccessful. Error %d", result.getErrorCode());
        } else {
            Log.d(TAG, "Connection to GmsCore successful.");
        }
        return result.isSuccess();
    } finally {
        TraceEvent.end("ChromeGoogleApiClientImpl:connectWithTimeout");
    }
}
 
Example 10
Source File: UtilityService.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends current Wearable Settings made in Smartphone app over to the Wearable companion app
 */
private void sendSettingsToWearable() {
    Log.d("Sending Settings to Wearable...");
    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(
            SettingsConstants.GOOGLE_API_CLIENT_TIMEOUT, TimeUnit.SECONDS);

    ArrayList<DataMap> settings = new ArrayList<>();
    DataMap settingsDataMap = getSettingsDataMap();
    settings.add(settingsDataMap);

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

        PutDataMapRequest dataMap = PutDataMapRequest.create(WearableConstants.SETTINGS_PATH);
        dataMap.getDataMap().putDataMapArrayList(WearableConstants.EXTRA_SETTINGS, settings);
        PutDataRequest request = dataMap.asPutDataRequest();

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

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

    } else {
        // GoogleApiClient connection error
        Log.e("Error connecting GoogleApiClient");
    }
}
 
Example 11
Source File: GoogleDriveClient.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void listFiles(DoDriveListFiles event) {
    try {
        String targetFolder = getDriveFolderName();
        ConnectionResult connectionResult = connect();
        if (connectionResult.isSuccess()) {
            DriveFolder folder = getDriveFolder(targetFolder);
            Query query = new Query.Builder()
                    .addFilter(Filters.and(
                            Filters.eq(SearchableField.MIME_TYPE, Export.BACKUP_MIME_TYPE),
                            Filters.eq(SearchableField.TRASHED, false)
                    ))
                    .build();
            DriveApi.MetadataBufferResult metadataBufferResult = folder.queryChildren(googleApiClient, query).await();
            if (metadataBufferResult.getStatus().isSuccess()) {
                List<DriveFileInfo> driveFiles = fetchFiles(metadataBufferResult);
                handleSuccess(driveFiles);
            } else {
                handleFailure(metadataBufferResult.getStatus());
            }
        } else {
            handleConnectionResult(connectionResult);
        }
    } catch (Exception e) {
        handleError(e);
    }
}
 
Example 12
Source File: DeviceClient.java    From SensorDashboard with Apache License 2.0 5 votes vote down vote up
private boolean validateConnection() {
    if (googleApiClient.isConnected()) {
        return true;
    }

    ConnectionResult result = googleApiClient.blockingConnect(CLIENT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);

    return result.isSuccess();
}
 
Example 13
Source File: RequestListenerService.java    From arcgis-runtime-demos-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessageReceived(final MessageEvent event) {
  Log.i("Test", "Received message!");
  // When a message is received, build a Google API client and connect it
  // The Wearable API is used for communicating with the Wear device, and the
  // Location API is used when collecting a new feature
  final GoogleApiClient client = new GoogleApiClient.Builder(this)
          .addApi(Wearable.API)
          .addApi(LocationServices.API)
          .build();
  ConnectionResult connectionResult = client.blockingConnect(30, TimeUnit.SECONDS);
  if (!connectionResult.isSuccess()) {
    Log.e("Test", "Failed to connect to GoogleApiClient");
  }
  Log.i("Test", "Successfully connected to Google Api Service");
  // Get the path of the message and handle it appropriately
  String path = event.getPath();
  switch(path) {
    case LAYER_REQUEST:
      handleLayerRequest(event, client);
      break;
    case FEATURE_TYPE_REQUEST:
      handleFeatureTypeRequest(event, client);
      break;
    case FEATURE_TYPE_RESPONSE:
      handleFeatureTypeResponse(event, client);
      break;
  }
}
 
Example 14
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 15
Source File: WatchFaceConfigListenerService.java    From american-sunsets-watch-face with Apache License 2.0 5 votes vote down vote up
@Override // WearableListenerService
public void onMessageReceived(MessageEvent messageEvent) {
    if (!messageEvent.getPath().equals(SunsetsWatchFaceUtil.PATH_WITH_FEATURE)) {
        return;
    }
    byte[] rawData = messageEvent.getData();
    // It's allowed that the message carries only some of the keys used in the config DataItem
    // and skips the ones that we don't want to change.
    DataMap configKeysToOverwrite = DataMap.fromByteArray(rawData);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Received watch face config message: " + configKeysToOverwrite);
    }

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Wearable.API).build();
    }
    if (!mGoogleApiClient.isConnected()) {
        ConnectionResult connectionResult =
                mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS);

        if (!connectionResult.isSuccess()) {
            Log.e(TAG, "Failed to connect to GoogleApiClient.");
            return;
        }
    }

    SunsetsWatchFaceUtil.overwriteKeysInConfigDataMap(mGoogleApiClient, configKeysToOverwrite);
}
 
Example 16
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 17
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 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: 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 20
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();
}