如何以包含数据的简单文本文件的形式将数据从 android 可穿戴设备发送到 phone?

How do I send data from an android wearable device to a phone in the form of a a simple text file containing data?

我有一个可穿戴应用程序。完成后的应用程序有 time/date、UUID、地理位置、选择的参数等数据显示在我面前,例如数据报告或在彼此下方的多个 TextView 中登录。就像一个清单。我希望将这些数据从我的可穿戴设备传输到我的 android phone.

现在我不得不问,WearOS 应用程序将 phone 与手表配对是否可以实现这样的功能?比如数据可以通过它发送吗?或者我到底能做什么?我在文档中读到了 Sync data items with the Data Layer API,但我不确定提供的代码片段是否有助于实现我想要的。

public class MainActivity extends Activity {
    private static final String COUNT_KEY = "com.example.key.count";
    private DataClient dataClient;
    private int count = 0;
    ...
    // Create a data map and put data in it
    private void increaseCounter() {
        PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");
        putDataMapReq.getDataMap().putInt(COUNT_KEY, count++);
        PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
        Task<DataItem> putDataTask = dataClient.putDataItem(putDataReq);
    }
  ...
}

我在文本视图中显示的数据是通过我调用的方法调用的,例如:getLocation、getUUID、getDateTime、getSelections 等...当我单击一个按钮时,我在 setOnClickListener 中调用它们。我希望将 TextView 中的这些数据放在一个文件或类似的文件中,并在生成它们时将它们从手表发送到手机 phone。

 private void getDateTime()
{
    SimpleDateFormat sdf_date = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf_time = new SimpleDateFormat("HH:mm:ss z");
    String currentDate= sdf_date.format(new Date());
    String currentTime= sdf_time.format(new Date());
    textView_date_time.setText("Date: "+currentDate+"\n"+"Time: "+currentTime);
}


 @SuppressLint("SetTextI18n")
private void getUUID()
{
// Retrieving the value using its keys the file name
// must be same in both saving and retrieving the data
        @SuppressLint("WrongConstant") SharedPreferences sh = getSharedPreferences("UUID_File", MODE_APPEND);
// The value will be default as empty string because for
// the very first time when the app is opened, there is nothing to show
        String theUUID = sh.getString(PREF_UNIQUE_ID, uniqueID);
// We can then use the data
        textView_UUID.setText("UUID: "+theUUID);
}
@SuppressLint("SetTextI18n")
private void getSelections()
{
     textView_data_selected.setText("Tool No.: "+c.getToolNo()+
             "\nTool Size: " +c.getToolSizeStr()+
             "\nFrom Mode: " +c.getCurrentModeStr()+
             "\nGoto Mode: " +c.getModeStr()+
             "\nMethod: " +c.getMethodStr()+
             "\nBit Duration: " +c.getBitDuration()+
             "\nUpper bound" +c.getUpStageValue()+
             "\nLower bound: "+c.getDownStageValue());
    
}

以上是我获取数据的方法示例。然后我在这里称呼他们:

    gps_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= 26) {
                    getLocation();
                    getDateTime();
                    getUUID();
                    getSelections();
                }
                else
                {
                    //ActivityCompat.requestPermissions(get_location.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                    Toast.makeText(get_location.this,"Build SDK too low",Toast.LENGTH_SHORT);
                }

            }
        });

现在我如何获取所有这些并将其从我的设备发送到 phone?

注意:我想作为文件发送的数据报告,我希望它像在后台完成的事情一样巧妙地完成。我不知道还能做什么或去哪里看。

如果您想使用数据层,您有两种选择,一种是使用 MessageClient API 将您的数据捆绑在一条消息中,然后将其直接发送到手持设备。这里最简单的方法是创建一个任意 JSONObject 并将您的数据序列化为 JSON 字符串,您可以将其填充到消息中。例如:

try {
    final JSONObject object = new JSONObject();
    object.put("heart_rate", (int) event.values[0]);
    object.put("timestamp", Instant.now().toString());
    new MessageSender("/MessageChannel", object.toString(), getApplicationContext()).start();
} catch (JSONException e) {
    Log.e(TAG, "Failed to create JSON object");
}

就我而言,我在 onSensorChanged 实现中执行此操作,但您可以在更新文本的任何位置插入它。

MessageSender 只是 MessageClient 的线程包装器:

import java.util.List;

class MessageSender extends Thread {
    private static final String TAG = "MessageSender";

    String path;
    String message;
    Context context;

    MessageSender(String path, String message, Context context) {
        this.path = path;
        this.message = message;
        this.context = context;
    }

    public void run() {
        try {
            Task<List<Node>> nodeListTask = Wearable.getNodeClient(context.getApplicationContext()).getConnectedNodes();
            List<Node> nodes = Tasks.await(nodeListTask);
            byte[] payload = message.getBytes();

            for (Node node : nodes) {
                String nodeId = node.getId();
                Task<Integer> sendMessageTask = Wearable.getMessageClient(context).sendMessage(nodeId, this.path, payload);

                try {
                    Tasks.await(sendMessageTask);
                } catch (Exception exception) {
                    // TODO: Implement exception handling
                    Log.e(TAG, "Exception thrown");
                }
            }
        } catch (Exception exception) {
            Log.e(TAG, exception.getMessage());
        }
    }
}

另一种选择是在数据层中创建数据项的嵌套层次结构并实施 DataClient.OnDataChangedListener on both sides, such that changes that are written in on one side are automatically synchronized with the other. You can find a good walkthrough on how to do that here

对于您的具体情况,将其打包在 JSON 对象中可能是最简单的。写入您喜欢的文件格式后,您可以在手持设备端实现,而无需涉及磨损端。