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

The following examples show how to use com.google.android.gms.common.api.GoogleApiClient#isConnected() . 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
/**
 * 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: GoogleApiClientBridge.java    From friendspell with Apache License 2.0 5 votes vote down vote up
public void unsubscribe(String token, MessageListener listener, ResultCallback<Status> callback) {
  GoogleApiClient googleApiClient = clients.get(token);
  if (googleApiClient.isConnected()) {
    Nearby.Messages.unsubscribe(googleApiClient, listener)
        .setResultCallback(callback);
  }
}
 
Example 9
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 10
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 11
Source File: WearableApi.java    From LibreAlarm with GNU General Public License v3.0 5 votes vote down vote up
private static boolean sendData(GoogleApiClient client, PutDataMapRequest putDataMapReq, ResultCallback<DataApi.DataItemResult> listener) {
    if (client.isConnected()) {
        Log.i(TAG, "update settings");
        putDataMapReq.setUrgent();
        PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
        PendingResult<DataApi.DataItemResult> pR =
                Wearable.DataApi.putDataItem(client, putDataReq);
        if (listener != null) pR.setResultCallback(listener);
        return true;
    }
    return false;
}
 
Example 12
Source File: LogoutHelper.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
private static void logoutGoogle(GoogleApiClient mGoogleApiClient, FragmentActivity fragmentActivity) {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = GoogleApiHelper.createGoogleApiClient(fragmentActivity);
    }

    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }

    final GoogleApiClient finalMGoogleApiClient = mGoogleApiClient;
    mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            if (finalMGoogleApiClient.isConnected()) {
                Auth.GoogleSignInApi.signOut(finalMGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        if (status.isSuccess()) {
                            LogUtil.logDebug(TAG, "User Logged out from Google");
                        } else {
                            LogUtil.logDebug(TAG, "Error Logged out from Google");
                        }
                    }
                });
            }
        }

        @Override
        public void onConnectionSuspended(int i) {
            LogUtil.logDebug(TAG, "Google API Client Connection Suspended");
        }
    });
}
 
Example 13
Source File: ActivityUtils.java    From CumulusTV with MIT License 5 votes vote down vote up
public static void syncFile(Activity activity, GoogleApiClient gapi) {
    if (DEBUG) {
    Log.d(TAG, "About to sync a file");
    }
    if (gapi == null && mCloudStorageProvider.connect(activity) != null) {
        gapi = mCloudStorageProvider.connect(activity);
    } else if(mCloudStorageProvider.connect(activity) == null) {
        // Is not existent
        Toast.makeText(activity, "There is no Google Play Service", Toast.LENGTH_SHORT).show();
        return;
    }
    if (gapi.isConnected()) {
        IntentSender intentSender = Drive.DriveApi
                .newOpenFileActivityBuilder()
                .setMimeType(new String[]{"application/json", "text/*"})
                .build(gapi);
        try {
            if (DEBUG) {
                Log.d(TAG, "About to start activity");
            }
            activity.startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null, 0, 0,
                    0);
            if (DEBUG) {
                Log.d(TAG, "Activity activated");
            }
        } catch (IntentSender.SendIntentException e) {
            if (DEBUG) {
                Log.w(TAG, "Unable to send intent", e);
            }
            e.printStackTrace();
        }
    } else {
        Toast.makeText(activity, R.string.toast_msg_wait_google_api_client,
                Toast.LENGTH_SHORT).show();
    }
}
 
Example 14
Source File: GooglePlayServices.java    From JayPS-AndroidApp with MIT License 4 votes vote down vote up
@Override
public void removeActivityUpdates(GoogleApiClient client, PendingIntent intent) {
    if(client.isConnected()) {
        ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(client, intent);
    }
}
 
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: 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 17
Source File: UtilityService.java    From PowerSwitch_Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 *
 * @param rooms     List containing Rooms from Database
 * @param receivers List containing Receivers from Database
 */
private void sendDataToWearable(List<Room> rooms, List<Receiver> receivers, List<Button> buttons, List<Scene>
        scenes) {
    Log.d("Sending new Data 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> data = new ArrayList<>();

    ArrayList<DataMap> roomData = new ArrayList<>();
    ArrayList<DataMap> receiverData = new ArrayList<>();
    ArrayList<DataMap> buttonData = new ArrayList<>();
    ArrayList<DataMap> sceneData = new ArrayList<>();

    for (Room room : rooms) {
        roomData.add(convertToDataMap(room));
        data.add(convertToDataMap(room));
    }

    for (Receiver receiver : receivers) {
        receiverData.add(convertToDataMap(receiver));
        data.add(convertToDataMap(receiver));
    }

    for (Button button : buttons) {
        buttonData.add(convertToDataMap(button));
        data.add(convertToDataMap(button));
    }

    for (Scene scene : scenes) {
        sceneData.add(convertToDataMap(scene));
        data.add(convertToDataMap(scene));
    }

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

        PutDataMapRequest dataMap = PutDataMapRequest.create(WearableConstants.DATA_PATH);
        dataMap.getDataMap().putDataMapArrayList(WearableConstants.EXTRA_DATA, data);
        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 data using DataApi (error code = %d)",
                    result.getStatus().getStatusCode()));
        } else {
            Log.d("Update data sent");
        }

    } else {
        // GoogleApiClient connection error
        Log.e("Error connecting GoogleApiClient");
    }

}
 
Example 18
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 19
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 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();
}