com.google.android.gms.nearby.connection.Connections Java Examples

The following examples show how to use com.google.android.gms.nearby.connection.Connections. 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: 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 #3
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 #4
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 #5
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 #6
Source File: PlayPianoPresenter.java    From android-things-distributed-piano with Apache License 2.0 5 votes vote down vote up
private void sendNote(final double frequency) {
    if (!googleApiClient.isConnected()) {
        view.showApiNotConnected();

        return;
    }
    Nearby.Connections.sendReliableMessage(googleApiClient, otherEndpointId, toByteArray(frequency));
}
 
Example #7
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
public void onEndpointFound(String endpointId, String deviceId, final String serviceId, String endpointName) {
    byte[] payload = null;

    Nearby.Connections.sendConnectionRequest( mGoogleApiClient, deviceId, endpointId, payload, new Connections.ConnectionResponseCallback() {

        @Override
        public void onConnectionResponse(String s, Status status, byte[] bytes) {
            if( status.isSuccess() ) {
                mStatusText.setText( "Connected to: " + s );
                Nearby.Connections.stopDiscovery(mGoogleApiClient, serviceId);
                mRemoteHostEndpoint = s;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                mSendTextContainer.setVisibility(View.VISIBLE);

                if( !mIsHost ) {
                    mIsConnected = true;
                }
            } else {
                mStatusText.setText( "Connection to " + s + " failed" );
                if( !mIsHost ) {
                    mIsConnected = false;
                }
            }
        }
    }, this );
}
 
Example #8
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void sendMessage( String message ) {
    if( mIsHost ) {
        Nearby.Connections.sendReliableMessage(mGoogleApiClient, mRemotePeerEndpoints, message.getBytes());
        mMessageAdapter.add(message);
        mMessageAdapter.notifyDataSetChanged();
    } else {
        Nearby.Connections.sendReliableMessage( mGoogleApiClient, mRemoteHostEndpoint, ( Nearby.Connections.getLocalDeviceId( mGoogleApiClient ) + " says: " + message ).getBytes() );
    }
}
 
Example #9
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 #10
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 #11
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
@Override
protected void onStop() {
    super.onStop();
    if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
        Nearby.Connections.stopAdvertising(mGoogleApiClient);
        mGoogleApiClient.disconnect();
    }
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: RobocarAdvertiser.java    From robocar with Apache License 2.0 5 votes vote down vote up
@Override
protected void onNearbyConnectionInitiated(final String endpointId,
        ConnectionInfo connectionInfo) {
    super.onNearbyConnectionInitiated(endpointId, connectionInfo);
    if (mCompanionConnectionLiveData.getValue() != null) {
        // We already have a companion trying to connect. Reject this one.
        Nearby.Connections.rejectConnection(mGoogleApiClient, endpointId);
        return;
    }


    DiscovererInfo info = DiscovererInfo.parse(connectionInfo.getEndpointName());
    if (info == null || isNotTheDroidWeAreLookingFor(info)) {
        // Discoverer looks malformed, or doesn't match our previous paired companion.
        Nearby.Connections.rejectConnection(mGoogleApiClient, endpointId);
        return;
    }

    // Store the endpoint and accept.
    CompanionConnection connection = new CompanionConnection(endpointId, info, this);
    connection.setAuthToken(connectionInfo.getAuthenticationToken());
    connection.setState(ConnectionState.AUTH_ACCEPTED);
    mCompanionConnectionLiveData.setValue(connection);

    Nearby.Connections.acceptConnection(mGoogleApiClient, endpointId, mInternalPayloadListener)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.d(TAG, "Accepted connection. " + endpointId);
                        // TODO implement a timeout
                    } else {
                        Log.d(TAG, "Accept connection failed." + endpointId);
                        // revert state
                        clearCompanionEndpoint();
                    }
                }
            });
}
 
Example #17
Source File: RobocarAdvertiser.java    From robocar with Apache License 2.0 5 votes vote down vote up
public final void stopAdvertising() {
    if (mAdvertisingLiveData.getValue()) {
        mAdvertisingLiveData.setValue(false);
        // if we're not connected, we should already have lost advertising
        if (mGoogleApiClient.isConnected()) {
            Nearby.Connections.stopAdvertising(mGoogleApiClient);
        }
    }
}
 
Example #18
Source File: RobocarAdvertiser.java    From robocar with Apache License 2.0 5 votes vote down vote up
public final void startAdvertising() {
    if (!mGoogleApiClient.isConnected()) {
        Log.d(TAG, "Google Api Client not connected");
        return;
    }
    if (mAdvertisingInfo == null) {
        Log.d(TAG, "Can't start advertising, no advertising info.");
        return;
    }
    if (mAdvertisingLiveData.getValue()) {
        Log.d(TAG, "Already advertising");
        return;
    }

    // Pre-emptively set this so the check above catches calls while we wait for a result.
    mAdvertisingLiveData.setValue(true);
    Nearby.Connections.startAdvertising(mGoogleApiClient, mAdvertisingInfo.getAdvertisingName(),
            SERVICE_ID, mLifecycleCallback, new AdvertisingOptions(STRATEGY))
            .setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
                @Override
                public void onResult(@NonNull StartAdvertisingResult startAdvertisingResult) {
                    Status status = startAdvertisingResult.getStatus();
                    if (status.isSuccess()) {
                        Log.d(TAG, "Advertising started.");
                        mAdvertisingLiveData.setValue(true);
                    } else {
                        Log.d(TAG, String.format("Failed to start advertising. %d, %s",
                                status.getStatusCode(), status.getStatusMessage()));
                        // revert state
                        mAdvertisingLiveData.setValue(false);
                    }
                }
            });
}
 
Example #19
Source File: PianoPresenter.java    From android-things-distributed-piano with Apache License 2.0 5 votes vote down vote up
private void startAdvertising() {
    Log.d(TAG, "startAdvertising");
    if (!isConnectedToNetwork()) {
        Log.d(TAG, "startAdvertising: not connected to WiFi network.");
        return;
    }

    List<AppIdentifier> appIdentifierList = new ArrayList<>();
    appIdentifierList.add(new AppIdentifier(packageName));
    AppMetadata appMetadata = new AppMetadata(appIdentifierList);
    Nearby.Connections.startAdvertising(googleApiClient, serviceId, appMetadata, 0L, this)
            .setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
                @Override
                public void onResult(@NonNull Connections.StartAdvertisingResult result) {
                    Log.d(TAG, "startAdvertising:onResult:" + result);
                    if (result.getStatus().isSuccess()) {
                        Log.d(TAG, "startAdvertising:onResult: SUCCESS");

                    } else {
                        Log.d(TAG, "startAdvertising:onResult: FAILURE ");
                        int statusCode = result.getStatus().getStatusCode();
                        if (statusCode == ConnectionsStatusCodes.STATUS_ALREADY_ADVERTISING) {
                            Log.d(TAG, "STATUS_ALREADY_ADVERTISING");
                        } else {
                            Log.d(TAG, "STATE_READY");
                        }
                    }
                }
            });
}
 
Example #20
Source File: PlayPianoPresenter.java    From android-things-distributed-piano with Apache License 2.0 5 votes vote down vote up
private void sendStop() {
    if (!googleApiClient.isConnected()) {
        view.showApiNotConnected();
        return;
    }
    Nearby.Connections.sendReliableMessage(googleApiClient, otherEndpointId, toByteArray(-1));

}
 
Example #21
Source File: PlayPianoPresenter.java    From android-things-distributed-piano with Apache License 2.0 5 votes vote down vote up
private void startDiscovery() {
    Log.d(TAG, "startDiscovery");
    if (!isConnectedToNetwork()) {
        Log.d(TAG, "startDiscovery: not connected to WiFi network.");
        return;
    }

    Nearby.Connections.startDiscovery(googleApiClient, serviceId, TIMEOUT_DISCOVER, this)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (!isViewAttached()) {
                        return;
                    }
                    if (status.isSuccess()) {
                        Log.d(TAG, "startDiscovery:onResult: SUCCESS");
                    } else {
                        Log.d(TAG, "startDiscovery:onResult: FAILURE");

                        int statusCode = status.getStatusCode();
                        if (statusCode == ConnectionsStatusCodes.STATUS_ALREADY_DISCOVERING) {
                            Log.d(TAG, "STATUS_ALREADY_DISCOVERING");
                        }
                    }
                }
            });
}
 
Example #22
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 4 votes vote down vote up
/**
 * Stop discovering Nearby Connections.
 */
public void stopDiscovery(String serviceId) {
    mState = STATE_IDLE;
    Nearby.Connections.stopDiscovery(mGoogleApiClient, serviceId);
}
 
Example #23
Source File: NearbyClient.java    From 8bitartist with Apache License 2.0 4 votes vote down vote up
/**
 * Stop advertising for Nearby connections.
 */
public void stopAdvertising() {
    mState = STATE_IDLE;
    Nearby.Connections.stopAdvertising(mGoogleApiClient);
}