com.google.android.gms.nearby.Nearby Java Examples

The following examples show how to use com.google.android.gms.nearby.Nearby. 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: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionRequest(final String remoteEndpointId, final String remoteDeviceId, final String remoteEndpointName, byte[] payload) {
    if( mIsHost ) {
        Nearby.Connections.acceptConnectionRequest( mGoogleApiClient, remoteEndpointId, payload, this ).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if( status.isSuccess() ) {
                    if( !mRemotePeerEndpoints.contains( remoteEndpointId ) ) {
                        mRemotePeerEndpoints.add( remoteEndpointId );
                    }

                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                    mMessageAdapter.notifyDataSetChanged();
                    sendMessage(remoteDeviceId + " connected!");

                    mSendTextContainer.setVisibility( View.VISIBLE );
                }
            }
        });
    } else {
        Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId );
    }
}
 
Example #2
Source File: GoogleApiClientBridge.java    From friendspell with Apache License 2.0 6 votes vote down vote up
public String init(
    Activity activity,
    GoogleApiClient.ConnectionCallbacks connectedListener,
    GoogleApiClient.OnConnectionFailedListener connectionFailedListener) {
  // Configure sign-in to request the user's ID, email address, and basic profile. ID and
  // basic profile are included in DEFAULT_SIGN_IN.
  GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
          .requestEmail()
          .requestId()
          .requestProfile()
          .build();

  GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity)
      .addConnectionCallbacks(connectedListener)
      .addOnConnectionFailedListener(connectionFailedListener)
      .addApi(Plus.API)
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
      .addApi(Nearby.MESSAGES_API)
      .build();
  String token = UUID.randomUUID().toString();
  clients.put(token, googleApiClient);
  return token;
}
 
Example #3
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 6 votes vote down vote up
/**
 * Begin discovering Nearby Connections.
 *
 * @param serviceId the ID of advertising services to discover.
 */
public void startDiscovery(String serviceId) {
    Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, 0L,
            myEndpointDiscoveryListener)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.d(TAG, "Started discovery.");
                        mState = STATE_DISCOVERING;
                    } else {
                        Log.w(TAG, "Failed to start discovery: " + status);
                        mState = STATE_IDLE;
                    }
                }
            });
}
 
Example #4
Source File: PianoPresenter.java    From android-things-distributed-piano with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionRequest(final String endpointId, String deviceId, String endpointName, byte[] payload) {
    Log.d(TAG, "onConnectionRequest");

    Nearby.Connections.acceptConnectionRequest(googleApiClient, endpointId, payload, this)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.d(TAG, "acceptConnectionRequest: SUCCESS");

                    } else {
                        Log.d(TAG, "acceptConnectionRequest: FAILURE");
                    }
                }
            });
}
 
Example #5
Source File: NearbyBackgroundSubscription.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
protected void onConnected() {
    PendingResult<Status> pendingResult = null;
    String actionStr = null;
    if (mAction == SUBSCRIBE) {
        pendingResult = Nearby.Messages.subscribe(
                getGoogleApiClient(), createNearbySubscribeIntent(), createSubscribeOptions());
        actionStr = "background subscribe";
    } else {
        pendingResult = Nearby.Messages.unsubscribe(
                getGoogleApiClient(), createNearbySubscribeIntent());
        actionStr = "background unsubscribe";
    }
    pendingResult.setResultCallback(new SimpleResultCallback(actionStr) {
        @Override
        public void onResult(final Status status) {
            super.onResult(status);
            disconnect();
            if (mCallback != null) {
                mCallback.run();
            }
        }
    });
}
 
Example #6
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 6 votes vote down vote up
/**
 * Begin advertising for Nearby Connections.
 */
public void startAdvertising() {
    long NO_TIMEOUT = 0L;

    Nearby.Connections.startAdvertising(mGoogleApiClient, null, null,
            NO_TIMEOUT, myConnectionRequestListener)
            .setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
                @Override
                public void onResult(Connections.StartAdvertisingResult result) {
                    if (result.getStatus().isSuccess()) {
                        Log.d(TAG, "Advertising as " +
                                result.getLocalEndpointName());
                        mState = STATE_ADVERTISING;
                    } else {
                        Log.w(TAG, "Failed to start advertising: " +
                                result.getStatus());
                        mState = STATE_IDLE;
                    }
                }
            });
}
 
Example #7
Source File: MainActivity.java    From nearby-beacons with MIT License 6 votes vote down vote up
private void subscribe() {
    Log.d(TAG, "Subscribing…");
    SubscribeOptions options = new SubscribeOptions.Builder()
            .setStrategy(Strategy.BLE_ONLY)
            .build();
    //Active subscription for foreground messages
    Nearby.Messages.subscribe(mGoogleApiClient,
            mMessageListener, options);

    //Passive subscription for background messages
    Intent serviceIntent = new Intent(this, BeaconService.class);
    PendingIntent trigger = PendingIntent.getService(this, 0,
            serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    ResultCallback<Status> callback = new BackgroundRegisterCallback();
    Nearby.Messages.subscribe(mGoogleApiClient, trigger, options)
            .setResultCallback(callback);

}
 
Example #8
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void initViews() {
    mStatusText = (TextView) findViewById( R.id.text_status );
    mConnectionButton = (Button) findViewById( R.id.button_connection );
    mSendButton = (Button) findViewById( R.id.button_send );
    mListView = (ListView) findViewById( R.id.list );
    mSendTextContainer = (ViewGroup) findViewById( R.id.send_text_container );
    mSendEditText = (EditText) findViewById( R.id.edit_text_send );
    mTypeSpinner = (Spinner) findViewById( R.id.spinner_type );

    setupButtons();
    setupConnectionTypeSpinner();
    setupMessageList();

    mGoogleApiClient = new GoogleApiClient.Builder( this )
            .addConnectionCallbacks( this )
            .addOnConnectionFailedListener( this )
            .addApi( Nearby.CONNECTIONS_API )
            .build();
}
 
Example #9
Source File: MainActivity.java    From connectivity-samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle bundle) {
  super.onCreate(bundle);
  setContentView(R.layout.activity_main);

  findOpponentButton = findViewById(R.id.find_opponent);
  disconnectButton = findViewById(R.id.disconnect);
  rockButton = findViewById(R.id.rock);
  paperButton = findViewById(R.id.paper);
  scissorsButton = findViewById(R.id.scissors);

  opponentText = findViewById(R.id.opponent_name);
  statusText = findViewById(R.id.status);
  scoreText = findViewById(R.id.score);

  TextView nameView = findViewById(R.id.name);
  nameView.setText(getString(R.string.codename, codeName));

  connectionsClient = Nearby.getConnectionsClient(this);

  resetGame();
}
 
Example #10
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void disconnect() {
    if( !isConnectedToNetwork() )
        return;

    if( mIsHost ) {
        sendMessage( "Shutting down host" );
        Nearby.Connections.stopAdvertising( mGoogleApiClient );
        Nearby.Connections.stopAllEndpoints( mGoogleApiClient );
        mIsHost = false;
        mStatusText.setText( "Not connected" );
        mRemotePeerEndpoints.clear();
    } else {
        if( !mIsConnected || TextUtils.isEmpty( mRemoteHostEndpoint ) ) {
            Nearby.Connections.stopDiscovery( mGoogleApiClient, getString( R.string.service_id ) );
            return;
        }

        sendMessage( "Disconnecting" );
        Nearby.Connections.disconnectFromEndpoint( mGoogleApiClient, mRemoteHostEndpoint );
        mRemoteHostEndpoint = null;
        mStatusText.setText( "Disconnected" );
    }

    mIsConnected = false;
}
 
Example #11
Source File: NearbyBackgroundSubscription.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@Override
protected void onConnected() {
    PendingResult<Status> pendingResult = null;
    String actionStr = null;
    if (mAction == SUBSCRIBE) {
        pendingResult = Nearby.Messages.subscribe(
                getGoogleApiClient(), createNearbySubscribeIntent(), createSubscribeOptions());
        actionStr = "background subscribe";
    } else {
        pendingResult = Nearby.Messages.unsubscribe(
                getGoogleApiClient(), createNearbySubscribeIntent());
        actionStr = "background unsubscribe";
    }
    pendingResult.setResultCallback(new SimpleResultCallback(actionStr) {
        @Override
        public void onResult(final Status status) {
            super.onResult(status);
            disconnect();
            if (mCallback != null) {
                mCallback.run();
            }
        }
    });
}
 
Example #12
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    if (mGoogleApiClient == null) {
        LogUtils.LOGE("***> fragment onStart", "here");
        mActivity.getPreferences(Context.MODE_PRIVATE)
                .registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                .addApi(Nearby.MESSAGES_API)
                .addConnectionCallbacks(mConnectionCallbacks)
                .addOnConnectionFailedListener(mConnectionFailedListener)
                .build();
        mGoogleApiClient.connect();
    }
}
 
Example #13
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
/**
 * Send a reliable message to the Host from a Client.
 */
public void sendMessageToHost(String message) {
    try {
        byte[] payload = message.getBytes("UTF-8");
        Nearby.Connections.sendReliableMessage(mGoogleApiClient,
                mHostId, payload);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Cannot encode " + message + " to UTF-8?");
    }
}
 
Example #14
Source File: NearbyForegroundSubscription.java    From 365browser with Apache License 2.0 5 votes vote down vote up
void unsubscribe() {
    if (!getGoogleApiClient().isConnected()) {
        mShouldSubscribe = false;
        return;
    }
    Nearby.Messages.unsubscribe(getGoogleApiClient(), MESSAGE_LISTENER)
            .setResultCallback(new SimpleResultCallback("foreground unsubscribe"));
}
 
Example #15
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void discover() {
    if( !isConnectedToNetwork() )
        return;

    String serviceId = getString( R.string.service_id );
    Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, 10000L, this).setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        mStatusText.setText( "Discovering" );
                    }
                }
            });
}
 
Example #16
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void advertise() {
    if( !isConnectedToNetwork() )
        return;

    String name = "Nearby Advertising";

    Nearby.Connections.startAdvertising( mGoogleApiClient, name, null, CONNECTION_TIME_OUT, this ).setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
        @Override
        public void onResult(Connections.StartAdvertisingResult result) {
            if (result.getStatus().isSuccess()) {
                mStatusText.setText("Advertising");
            }
        }
    });
}
 
Example #17
Source File: MainActivity.java    From nearby-beacons with MIT License 5 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    //Once connected, we have to check that the user has opted in
    Runnable runOnSuccess = new Runnable() {
        @Override
        public void run() {
            //Subscribe once user permission is verified
            subscribe();
        }
    };
    ResultCallback<Status> callback =
            new ErrorCheckingCallback(runOnSuccess);
    Nearby.Messages.getPermissionStatus(mGoogleApiClient)
            .setResultCallback(callback);
}
 
Example #18
Source File: MainActivity.java    From nearby-beacons with MIT License 5 votes vote down vote up
@Override
protected void onStop() {
    super.onStop();
    //Tear down Play Services connection
    if (mGoogleApiClient.isConnected()) {
        Log.d(TAG, "Un-subscribing…");
        Nearby.Messages.unsubscribe(
                mGoogleApiClient,
                mMessageListener);
        mAdapter.clear();

        mGoogleApiClient.disconnect();
    }
}
 
Example #19
Source File: MainActivity.java    From nearby-beacons with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView list = (ListView) findViewById(R.id.list);

    mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
    list.setAdapter(mAdapter);
    list.setOnItemClickListener(this);

    //Construct a connection to Play Services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Nearby.MESSAGES_API)
            .build();

    //When launching from a notification link
    if (BeaconService.ACTION_DISMISS.equals(getIntent().getAction())) {
        //Fire a clear action to the service
        Intent intent = new Intent(this, BeaconService.class);
        intent.setAction(BeaconService.ACTION_DISMISS);
        startService(intent);
    }

}
 
Example #20
Source File: BeaconService.java    From nearby-beacons with MIT License 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null) return START_NOT_STICKY;

    if (!ACTION_DISMISS.equals(intent.getAction())) {
        //Convert the incoming intent into a message
        Nearby.Messages.handleIntent(intent, mMessageListener);
    } else {
        mNotificationManager.cancel(NOTIFICATION_ID);
        stopSelf();
    }

    return START_NOT_STICKY;
}
 
Example #21
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
public void onConnectionRequest(final String remoteEndpointId, final
String remoteName,
                                byte[] payload) {
    Log.d(TAG, "onConnectionRequest:" + remoteEndpointId + ":" + remoteName);

    if (mIsHost) {
        // The host accepts all connection requests it gets.
        Nearby.Connections.acceptConnectionRequest(mGoogleApiClient,
                remoteEndpointId,
                null, this).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                Log.d(TAG, "acceptConnectionRequest:" + status + ":" +
                        remoteEndpointId);
                if (status.isSuccess()) {
                    Toast.makeText(mContext, "Connected to " + remoteName,
                            Toast.LENGTH_SHORT).show();

                    // Record connection
                    DrawingParticipant participant =
                            new DrawingParticipant(remoteEndpointId,
                            remoteName);
                    mConnectedClients.put(remoteEndpointId, participant);

                    // Notify listener
                    mListener.onConnectedToEndpoint(remoteEndpointId, remoteName);
                } else {
                    Toast.makeText(mContext, "Failed to connect to: " + remoteName,
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    } else {
        // Clients should not be advertising and will reject all connection requests.
        Log.w(TAG, "Connection Request to Non-Host Device - Rejecting");
        Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
    }
}
 
Example #22
Source File: NearbyForegroundSubscription.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
void unsubscribe() {
    if (!getGoogleApiClient().isConnected()) {
        mShouldSubscribe = false;
        return;
    }
    Nearby.Messages.unsubscribe(getGoogleApiClient(), mMessageListener)
            .setResultCallback(new SimpleResultCallback("foreground unsubscribe"));
}
 
Example #23
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
/**
 * Send a connection request to a remote endpoint. If the request is successful, notify the
 * listener and add the connection to the Set.  Otherwise, show an error Toast.
 *
 * @param endpointId   the endpointID to connect to.
 * @param endpointName the name of the endpoint to connect to.
 */
private void connectTo(final String endpointId,
                       final String endpointName) {
    Log.d(TAG, "connectTo:" + endpointId);
    Nearby.Connections.sendConnectionRequest(mGoogleApiClient, null,
            endpointId, null,
            new Connections.ConnectionResponseCallback() {
                @Override
                public void onConnectionResponse(String remoteEndpointId, Status status,
                                                 byte[] payload) {
                    Log.d(TAG, "onConnectionResponse:" +
                            remoteEndpointId + ":" + status);
                    if (status.isSuccess()) {
                        // Connection successful, notify listener
                        Toast.makeText(mContext, "Connected to: " + endpointName,
                                Toast.LENGTH_SHORT).show();

                        mHostId = remoteEndpointId;
                        mConnectedClients.put(remoteEndpointId,
                                new DrawingParticipant(
                                remoteEndpointId, endpointName));
                        mListener.onConnectedToEndpoint(mHostId,
                                endpointName);
                    } else {
                        // Connection not successful, show error
                        Toast.makeText(mContext, "Error: failed to connect.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }, this);
}
 
Example #24
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
/**
 * Send a message to a specific participant.
 *
 * @param endpointId the endpoint ID of the participant that will
 *                   receive the message.
 * @param message    String to send as payload.
 */
public void sendMessageTo(String endpointId, String message) {

    try {
        byte[] payload = message.getBytes("UTF-8");
        Log.d(TAG, "Sending message: " + message);
        Nearby.Connections.sendReliableMessage(mGoogleApiClient,
                endpointId, payload);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Cannot encode " + message + " to UTF-8?");
    }
}
 
Example #25
Source File: MainActivity.java    From connectivity-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Subscribes to messages from nearby devices and updates the UI if the subscription either
 * fails or TTLs.
 */
private void subscribe() {
    Log.i(TAG, "Subscribing");
    mNearbyDevicesArrayAdapter.clear();
    SubscribeOptions options = new SubscribeOptions.Builder()
            .setStrategy(PUB_SUB_STRATEGY)
            .setCallback(new SubscribeCallback() {
                @Override
                public void onExpired() {
                    super.onExpired();
                    Log.i(TAG, "No longer subscribing");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mSubscribeSwitch.setChecked(false);
                        }
                    });
                }
            }).build();

    Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.i(TAG, "Subscribed successfully.");
                    } else {
                        logAndShowSnackbar("Could not subscribe, status = " + status);
                        mSubscribeSwitch.setChecked(false);
                    }
                }
            });
}
 
Example #26
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new NearbyClient.
 *
 * @param context  the creating context, generally an Activity or Fragment.
 * @param isHost   true if this client should act as host, false otherwise.
 * @param listener a NearbyClientListener to be notified of events.
 */
public NearbyClient(Context context, boolean isHost, NearbyClientListener listener) {
    mContext = context;
    mIsHost = isHost;
    mListener = listener;
    mState = STATE_IDLE;

    mGoogleApiClient = new GoogleApiClient.Builder(mContext, this, this)
            .addApi(Nearby.CONNECTIONS_API)
            .build();
    mGoogleApiClient.connect();
}
 
Example #27
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnected(@Nullable Bundle bundle) {
    LogUtils.LOGE(TAG, "GoogleApiClient connected");
    Nearby.Messages.getPermissionStatus(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                executePendingTasks();
            } else {
                handleUnsuccessfulNearbyResult(status);
            }
        }
    });
}
 
Example #28
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 5 votes vote down vote up
/**
 * Ends the subscription to messages from nearby devices. If successful, resets state. If not
 * successful, attempts to resolve any error related to Nearby permissions by
 * displaying an opt-in dialog.
 */
private void unsubscribe() {
    LogUtils.LOGE(TAG, "trying to unsubscribe");
    // Cannot proceed without a connected GoogleApiClient. Reconnect and execute the pending
    // task in onConnected().
    if (!mGoogleApiClient.isConnected()) {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    } else {
        Nearby.Messages.unsubscribe(mGoogleApiClient, mMessageListener)
                .setResultCallback(new ResultCallback<Status>() {

                    @Override
                    public void onResult(@NonNull Status status) {
                        if (mProgressDialog != null && mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }

                        if (status.isSuccess()) {
                            LogUtils.LOGE(TAG, "unsubscribed successfully");
                            updateSharedPreference(Constants.KEY_SUBSCRIPTION_TASK, Constants.TASK_NONE);
                        } else {
                            LogUtils.LOGE(TAG, "could not unsubscribe");
                            handleUnsuccessfulNearbyResult(status);
                        }
                    }
                });
    }
}
 
Example #29
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 5 votes vote down vote up
/**
 * Stops publishing device information to nearby devices. If successful, resets state. If not
 * successful, attempts to resolve any error related to Nearby permissions by displaying an
 * opt-in dialog.
 */
private void unpublish() {
    LogUtils.LOGE(TAG, "trying to unpublish");
    // Cannot proceed without a connected GoogleApiClient. Reconnect and execute the pending task in onConnected().
    if (!mGoogleApiClient.isConnected()) {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    } else {
        if (mDeviceInfoMessage != null) {
            Nearby.Messages.unpublish(mGoogleApiClient, mDeviceInfoMessage)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                                mProgressDialog.dismiss();
                            }

                            if (status.isSuccess()) {
                                LogUtils.LOGE(TAG, "unpublished successfully");
                                updateSharedPreference(Constants.KEY_PUBLICATION_TASK, Constants.TASK_NONE);
                            } else {
                                LogUtils.LOGE(TAG, "could not unpublish");
                                handleUnsuccessfulNearbyResult(status);
                            }
                        }
                    });
        }
    }
}
 
Example #30
Source File: MessageFragment.java    From io16experiment-master with Apache License 2.0 5 votes vote down vote up
/**
 * Subscribes to messages from nearby devices. If not successful, attempts to resolve any error
 * related to Nearby permissions by displaying an opt-in dialog. Registers a callback which
 * updates state when the subscription expires.
 */
private void subscribe() {
    LogUtils.LOGE(TAG, "trying to subscribe");
    // Cannot proceed without a connected GoogleApiClient. Reconnect and execute the pending
    // task in onConnected().
    if (!mGoogleApiClient.isConnected()) {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    } else {
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(PUB_SUB_STRATEGY)
                .setCallback(new SubscribeCallback() {
                    @Override
                    public void onExpired() {
                        super.onExpired();
                        LogUtils.LOGE(TAG, "no longer subscribing");
                        updateSharedPreference(Constants.KEY_SUBSCRIPTION_TASK, Constants.TASK_NONE);
                    }
                }).build();

        Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        if (mProgressDialog != null && mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }

                        if (status.isSuccess()) {
                            LogUtils.LOGE(TAG, "subscribed successfully");
                        } else {
                            LogUtils.LOGE(TAG, "could not subscribe");
                            handleUnsuccessfulNearbyResult(status);
                        }
                    }
                });
    }
}