附近的连接2.0简单文件交换应用程序

时间:2017-10-31 18:38:18

标签: google-play-services google-nearby

我试图编写简单的android文件交换应用程序,主要使用来自https://developers.google.com/nearby/connections/android/exchange-data和Walkietalkie应用程序的代码段。

但我仍然坚持传输文件有效负载第二个sendPayload,onPayloadTransferUpdate仅在发送端调用。发现,广告,连接到端点,一切正常。发件人是"发送",但是Reciever只获取带有id和filename的字符串消息并等待(onPayloadTransferUpdate仅为第一个sendPayload调用2次)然后什么都没有,在发送者完成传输后断开连接。

public void sendFile(String uri) {
    File file = new File(uri);
    if (file.exists() && mEstablishedConnections.values().size() > 0) {
        for (Endpoint endpoint : mEstablishedConnections.values()) {
            try {
                // Open the ParcelFileDescriptor for this URI with read access.
                ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(Uri.fromFile(file), "r");

                Payload filePayload = Payload.fromFile(pfd);

                // Construct a simple message mapping the ID of the file payload to the desired filename.
                String payloadFilenameMessage = filePayload.getId() + ":" + Uri.fromFile(file).getLastPathSegment();

                // Send this message as a bytes payload.
                Nearby.Connections.sendPayload(mGoogleApiClient,
                        endpoint.getId(),
                        Payload.fromBytes(payloadFilenameMessage.getBytes("UTF-8")));

                // Finally, send the file payload.
                Nearby.Connections.sendPayload(mGoogleApiClient,
                        endpoint.getId(),
                        filePayload);


            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    } else {
        Log.e(TAG, "sendFile: EstablishedConnections == 0");
    }
}

private final PayloadCallback mPayloadCallback = new PayloadCallback() {

    @Override
    public void onPayloadReceived(String endpointId, Payload payload) {
        Log.d(TAG, String.format("onPayloadReceived(endpointId=%s, payload=%s)", endpointId, payload));

        try {
            if (payload.getType() == Payload.Type.BYTES) {
                Log.d(TAG, "onPayloadReceived: Payload.Type.BYTES");
                String payloadFilenameMessage = new String(payload.asBytes(), "UTF-8");
                Log.d(TAG, "onPayloadReceived: BYTES " + payloadFilenameMessage);
                addPayloadFilename(payloadFilenameMessage);
            } else if (payload.getType() == Payload.Type.FILE) {
                // Add this to our tracking map, so that we can retrieve the payload later.
                incomingFilePayloads.put(payload.getId(), payload);

                Log.d(TAG, "onPayloadReceived: Payload.Type.FILE");
            } else if (payload.getType() == Payload.Type.STREAM) {
                //payload.asStream().asInputStream()
                Log.d(TAG, "onPayloadReceived: Payload.Type.STREAM");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
        Log.d(TAG, String.format("onPayloadTransferUpdate(endpointId=%s, update=%s)",
                endpointId, update));

        switch(update.getStatus()) {
            case PayloadTransferUpdate.Status.IN_PROGRESS:
                break;
            case PayloadTransferUpdate.Status.SUCCESS:
                Log.d(TAG, "onPayloadTransferUpdate: SUCCESS");
                Payload payload = incomingFilePayloads.remove(update.getPayloadId());
                 if (payload != null && payload.getType() == Payload.Type.FILE) {
                    // Retrieve the filename that was received in a bytes payload.
                    String newFilename = filePayloadFilenames.remove(update.getPayloadId());
                    java.io.File payloadFile = payload.asFile().asJavaFile();

                    // Rename the file.
                    payloadFile.renameTo(new File(payloadFile.getParentFile(), newFilename));

                }

                break;
            case PayloadTransferUpdate.Status.FAILURE:
                Log.d(TAG, "onPayloadTransferUpdate: FAILURE");
                break;
        }
    }
}; 

除了google示例walkietalkie之外还有一个有效的例子吗?

发件人

  

D / ShareService:sendFile:filename message -7668342386822656500:a73ecba18dc6c8506ed89c1ed47c9948.mp4

     

D / ShareService:onPayloadTransferUpdate(endpointId = osUc,update = com.google.android.gms.nearby.connection.PayloadTransferUpdate@e16fc0a8)   D / ShareService:onPayloadTransferUpdate:57   D / ShareService:onPayloadTransferUpdate:1048576   D / DiscoveryActivity:onNext:ShareState {state ='发送',stateCode = 800}   D / ShareService:onPayloadTransferUpdate(endpointId = osUc,update = com.google.android.gms.nearby.connection.PayloadTransferUpdate@813731ce)   D / ShareService:onPayloadTransferUpdate:1055744   D / DiscoveryActivity:onNext:ShareState {state ='发送',stateCode = 800}   D / ShareService:onPayloadTransferUpdate(endpointId = osUc,update = com.google.android.gms.nearby.connection.PayloadTransferUpdate@81372a4c)   11-01 07:35:20.790 D / ShareService:onPayloadTransferUpdate:SUCCESS   11-01 07:35:41.587 D / ShareService:disconnectedFromEndpoint(endpoint = Endpoint {id = osUc,name = 87389})   11-01 07:35:41.587 D / ShareService:onEndpointDisconnected

收件人

  

D / ShareService:onConnectionResponse(endpointId = ABVq,result = com.google.android.gms.nearby.connection.ConnectionResolution@9edd5e3)   D / ShareService:connectedToEndpoint(endpoint = Endpoint {id = ABVq,name = 08043})   D / ShareService:onEndpointConnected   D / ShareService:stopDiscovering   D / ShareService:stopAdvertising

     

D / ShareService:onPayloadReceived(endpointId = ABVq,payload = com.google.android.gms.nearby.connection.Payload@516155e)   D / ShareService:onPayloadReceived:Payload.Type.BYTES   D / ShareService:onPayloadReceived:BYTES -7668342386822656500:a73ecba18dc6c8506ed89c1ed47c9948.mp4   D / ShareService:onPayloadTransferUpdate(endpointId = ABVq,update = com.google.android.gms.nearby.connection.PayloadTransferUpdate@ba6f47ac)   D / ShareService:onPayloadTransferUpdate:57   D / ShareService:onPayloadTransferUpdate(endpointId = ABVq,update = com.google.android.gms.nearby.connection.PayloadTransferUpdate@ba6f402a)   11-01 08:10:52.525 D / ShareService:onPayloadTransferUpdate:SUCCESS   11-01 08:11:12.355 D / ShareService:disconnectedFromEndpoint(endpoint = Endpoint {id = ABVq,name = 08043})   D / ShareService:onEndpointDisconnected

onPayloadTransferUpdate:第一次字符串传输的成功

延迟

Payload bytePayload = outgoingPayloads.remove(update.getPayloadId());
                            if (bytePayload != null && bytePayload.getType() == Payload.Type.BYTES) {
                                if (endpnt != null && filePayload != null) {
                                    try {
                                        Thread.sleep(10000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    Nearby.Connections.sendPayload(mGoogleApiClient,
                                            endpnt.getId(),
                                            filePayload);
                                }
                            }

文件:///data/data/com.package.name/files/folder/a73ecba18dc6c8506ed89c1ed47c9948.mp4

来源https://github.com/salexwm/FilesExchange

1 个答案:

答案 0 :(得分:2)

如果您需要,我可以提供一个工作示例,但您几乎拥有它。一些指示:

  1. 仅在完全发送BYTE标头后,在onPayloadTransferUpdate(SUCCESS)中发送FILE有效负载。订单不保证不同类型的有效负载。
  2. 在您获得FILE有效负载的onPayloadTransferUpdate(SUCCESS)之前,请不要断开连接。如果在传输过程中断开连接,则无法完全发送。
  3. 你应该做Uri.parse(uri),而不是Uri.fromFile(新文件(uri))。