Send file Google Wear to mobile

青春壹個敷衍的年華 提交于 2019-12-12 15:49:14

问题


I'm trying to send a file from my Google wear to my Nexus 5. I've read some tutorials and came up with the following code but my phone isn't receiving a file.

Mobile:

private GoogleApiClient mGoogleApiClient;
private int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    Log.d(TAG, "CONNECTING:");

    mGoogleApiClient.connect();
}

@Override
protected void onResume() {
    super.onStart();
}

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "CONNECTED");
    Toast.makeText(getApplicationContext(), "Connected.",
            Toast.LENGTH_LONG).show();
    Wearable.DataApi.addListener(mGoogleApiClient, this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
protected void onPause() {
    super.onPause();
    Wearable.DataApi.removeListener(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
}

@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Toast.makeText(getApplicationContext(), "Data changed.",
            Toast.LENGTH_LONG).show();
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_CHANGED &&
                event.getDataItem().getUri().getPath().equals("/txt")) {
            // Get the Asset object
            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            Asset asset = dataMapItem.getDataMap().getAsset("sensordataAsset");
            Log.d(TAG, "");

            ConnectionResult result =
                    mGoogleApiClient.blockingConnect(10000, TimeUnit.MILLISECONDS);
            if (!result.isSuccess()) {
                return;
            }

            // Convert asset into a file descriptor and block until it's ready
            InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
                    mGoogleApiClient, asset).await().getInputStream();
            mGoogleApiClient.disconnect();
            if (assetInputStream == null) {
                return;
            }

            // Get folder for output
            File storage = getApplicationContext().getFilesDir();
            Log.d(TAG, "Location:" + storage.toString());
            File dir = new File(storage.getAbsolutePath() + "/Clockwork/");
            if (!dir.exists()) {
                dir.mkdirs();
            } // Create folder if needed
            Log.d(TAG, dir.getAbsolutePath());

            // Read data from the Asset and write it to a file on external storage
            final File file = new File(dir, "sensordata.txt");
            if (!file.exists()) {
                file.mkdirs();
            }
            Log.d(TAG, file.getPath());

            try {
                FileOutputStream fOut = new FileOutputStream(file);
                int nRead;
                byte[] data = new byte[16384];
                while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
                    fOut.write(data, 0, nRead);
                }

                fOut.flush();
                fOut.close();
            } catch (Exception e) {
            }

            // Rescan folder to make it appear
            try {
                String[] paths = new String[1];
                paths[0] = file.getAbsolutePath();
                MediaScannerConnection.scanFile(this, paths, null, null);
            } catch (Exception e) {
            }
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

Wear:

public void sendTextFile() {

    readFromFile();
    FileInputStream fileInputStream = null;

    byte[] bFile = new byte[(int) file.length()];
    try {
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
    } catch (Exception e) {
        Log.e(TAG, "sendTextFile: " + e.toString());
    }

    connectGoogleApi();
    //Create an Asset from the byte array and set it via the DataApi
    Asset asset = Asset.createFromBytes(bFile);
    PutDataMapRequest dataMap = PutDataMapRequest.create("/txt");
    dataMap.getDataMap().putAsset("sensordataAsset", asset);
    PutDataRequest request = dataMap.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi
            .putDataItem(mGoogleApiClient, request);

}
private void connectGoogleApi() {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "CONNECTED");
    Toast.makeText(context, "Connected.",
            Toast.LENGTH_LONG).show();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

I've made a logger with the methods listed above. Can someone tell me what I'm doing wrong. Thanks in advance.


回答1:


add a key value in the datamap: map.put("timestamp", System.currentmillions()) your phone do not receive any change event, because you put the same data item into the data api queue, try to put a different item




回答2:


I solved it by replacing this

PutDataRequest putDataRequest = PutDataRequest.create("/image");
putDataRequest.putAsset("debugFile", asset);
Wearable.DataApi.putDataItem(client, putDataRequest);

with this

PutDataMapRequest dataMap = PutDataMapRequest.create("/image");
dataMap.getDataMap().putAsset("debugFile", asset);
PutDataRequest request = dataMap.asPutDataRequest();
PendingResult<DataItemResult> pendingResult = Wearable.DataApi.putDataItem(client, request);
pendingResult.setResultCallback(new ResultCallback<DataItemResult> () {
    @Override
    public void onResult(DataItemResult dataItemResult) {
        // something 
    }
} );

now it works for me




回答3:


Main error:

        // Read data from the Asset and write it to a file on external storage
        final File file = new File(dir, "sensordata.txt");
        if (!file.exists()) {
            file.mkdirs(); <---- you create a directory instead a file
        }

and that's why you see not the error.

            fOut.flush();
            fOut.close();
        } catch (Exception e) { <--- hide exception
        }

File exists as directory and a stream can't be open it

   FileOutputStream fOut = new FileOutputStream(file); <-- throw exception


来源:https://stackoverflow.com/questions/28808283/send-file-google-wear-to-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!