保存从Android Wear收到的DataItemAsset

时间:2015-02-04 05:25:37

标签: android wear-os android-wear-data-api

我对Android比较陌生。我将文件从Android Wear设备转移到手机,我通过PutDataRequest完成了该操作。在电话方面,我得到一个DataItemAsset,它可以使用Wearable.DataApi.getFdForAsset()为我提供文件描述符。我的问题是如何将此文件保存到外部存储?

谢谢!

1 个答案:

答案 0 :(得分:4)

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

(1)在手表方面,创建一个文本文件,并将其读入可以通过DataApi放置的资产:

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