1

I'm relatively new to Android. I'm transferring a file from an Android Wear device to a phone, which I did through PutDataRequest. On the phone side I get a DataItemAsset which can provide me a file descriptor using Wearable.DataApi.getFdForAsset(). My question is how do I save this file to external storage?

Thank you!

4

1 回答 1

4

以下是我如何设法将文本文件从 Android Wear 手表上传到配对的手机。可能有更简单的方法,但这对我有用。

(1) 在手表端,创建一个文本文件,并将其读入一个可以通过 DataApi 放入的 Asset:

public void SendTextFile()
{
    // Get folder for output
    File sdcard = Environment.getExternalStorageDirectory();
    File dir = new File(sdcard.getAbsolutePath()+ "/MyAppFolder/");
    if (!dir.exists()) {dir.mkdirs();} // Create folder if needed
    final File file = new File(dir, "test.txt");
    if (file.exists()) file.delete();

    // Write a text file to external storage on the watch
    try {
        Date now = new Date();
        long nTime = now.getTime();
        FileOutputStream fOut = new FileOutputStream(file);
        PrintStream ps = new PrintStream(fOut);
        ps.println("Time = "+Long.toString(nTime)); // A value that changes each time
        ps.close();
    } catch (Exception e) {
    }

    // Read the text file into a byte array
    FileInputStream fileInputStream = null;
    byte[] bFile = new byte[(int) file.length()];
    try {
        fileInputStream = new FileInputStream(file);
        fileInputStream.read(bFile);
        fileInputStream.close();
    } catch (Exception e) {
    }

    // Create an Asset from the byte array, and send it via the DataApi
    Asset asset = Asset.createFromBytes(bFile);
    PutDataMapRequest dataMap = PutDataMapRequest.create("/txt");
    dataMap.getDataMap().putAsset("com.example.company.key.TXT", asset);
    PutDataRequest request = dataMap.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi
            .putDataItem(mGoogleApiClient, request);
}

(2) 在移动端,接收资产并将其写回文件:

public void onDataChanged(DataEventBuffer dataEvents) {
    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("com.example.company.key.TXT");

            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 sdcard = Environment.getExternalStorageDirectory();
            File dir = new File(sdcard.getAbsolutePath() + "/MyAppFolder/");
            if (!dir.exists()) { dir.mkdirs(); } // Create folder if needed

            // Read data from the Asset and write it to a file on external storage
            final File file = new File(dir, "test.txt");
            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) {
            }
        }
    }
}

您还需要在清单的两端添加以下权限以写入外部存储:android.permission.WRITE_EXTERNAL_STORAGE

注意:需要注意的最令人沮丧的是:如果数据没有变化,则不会发生传输。因此,当您测试是否将相同的数据文件内容写入两次时,它只会在第一次出现 - 即使您从第一次运行中删除了该文件。我为 DataApi 的这个阴险功能浪费了好几个小时!这就是为什么我上面的代码将当前时间写入文本文件的原因。

此外,当然请确保您设置 GoogleApiClient 对象以连接、添加侦听器等,如下所述:http: //developer.android.com/training/wearables/data-layer/index.html

于 2015-02-05T23:30:15.663 回答