Java源码示例:com.google.android.gms.nearby.connection.Connections
示例1
@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");
}
}
});
}
示例2
/**
* 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;
}
}
});
}
示例3
/**
* 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;
}
}
});
}
示例4
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;
}
示例5
@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 );
}
}
示例6
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");
}
}
}
});
}
示例7
private void sendNote(final double frequency) {
if (!googleApiClient.isConnected()) {
view.showApiNotConnected();
return;
}
Nearby.Connections.sendReliableMessage(googleApiClient, otherEndpointId, toByteArray(frequency));
}
示例8
private void sendStop() {
if (!googleApiClient.isConnected()) {
view.showApiNotConnected();
return;
}
Nearby.Connections.sendReliableMessage(googleApiClient, otherEndpointId, toByteArray(-1));
}
示例9
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");
}
}
}
});
}
示例10
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);
}
}
});
}
示例11
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);
}
}
}
示例12
@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();
}
}
});
}
示例13
/**
* 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?");
}
}
示例14
/**
* 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?");
}
}
示例15
/**
* 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);
}
示例16
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);
}
}
示例17
@Override
protected void onStop() {
super.onStop();
if( mGoogleApiClient != null && mGoogleApiClient.isConnected() ) {
Nearby.Connections.stopAdvertising(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
}
示例18
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");
}
}
});
}
示例19
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" );
}
}
});
}
示例20
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() );
}
}
示例21
@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 );
}
示例22
/**
* Stop advertising for Nearby connections.
*/
public void stopAdvertising() {
mState = STATE_IDLE;
Nearby.Connections.stopAdvertising(mGoogleApiClient);
}
示例23
/**
* Stop discovering Nearby Connections.
*/
public void stopDiscovery(String serviceId) {
mState = STATE_IDLE;
Nearby.Connections.stopDiscovery(mGoogleApiClient, serviceId);
}