Как отправить файл а не текст?

У меня есть пример для отправки сообщения с телефона на часы. Как отправить и принять файл а не текст?

Отправка текста

public void onSend(View view) {
    final String text = tvMessage.getText().toString();

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            Collection<String> nodes = getNodes();
            LOGD(TAG, "Nodes: " + nodes.size());
            for (String node : nodes) {
                Task<ChannelClient.Channel> channelTask = Wearable.getChannelClient(getApplicationContext()).openChannel(node, CHANNEL_MSG);
                channelTask.addOnSuccessListener(new OnSuccessListener<ChannelClient.Channel>() {
                    @Override
                    public void onSuccess(ChannelClient.Channel channel) {
                        LOGD(TAG, "onSuccess " + channel.getNodeId());
                        Task<OutputStream> outputStreamTask = Wearable.getChannelClient(getApplicationContext()).getOutputStream(channel);
                        outputStreamTask.addOnSuccessListener(new OnSuccessListener<OutputStream>() {
                            @Override
                            public void onSuccess(OutputStream outputStream) {
                                LOGD(TAG, "output stream onSuccess");
                                try {
                                    outputStream.write(text.getBytes());
                                    outputStream.flush();
                                    outputStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            }
        }
    });
}

Прием на часах

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

    Wearable.getChannelClient(getApplicationContext()).registerChannelCallback(new ChannelClient.ChannelCallback() {
        @Override
        public void onChannelOpened(@NonNull ChannelClient.Channel channel) {
            super.onChannelOpened(channel);
            Log.d(TAG, "onChannelOpened");
            /**
             * input stream
             */
            Task<InputStream> inputStreamTask = Wearable.getChannelClient(getApplicationContext()).getInputStream(channel);
            inputStreamTask.addOnSuccessListener(new OnSuccessListener<InputStream>() {
                @Override
                public void onSuccess(final InputStream inputStream) {
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String text = "";
                                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                                int read;
                                byte[] data = new byte[1024];

                                while ((read = inputStream.read(data, 0, data.length)) != -1) {
                                    Log.d(TAG, "data length " + read); /** use Log.e to force print, if Log.d does not work */
                                    buffer.write(data, 0, read);

                                    buffer.flush();
                                    byte[] byteArray = buffer.toByteArray();

                                    text += new String(byteArray, StandardCharsets.UTF_8);

                                }
                                Log.d(TAG, "reading: " + text);
                                String finalText = text;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvMessage.setText(finalText);
                                        String URL = tvMessage.getText().toString();
                                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
                                        request.setTitle("wearOs.apk");
                                        request.setDescription("Downloading " + "wearOs.apk");
                                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                        request.allowScanningByMediaScanner();
                                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "wearOs.apk");
                                        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                                        manager.enqueue(request);

                                        File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+"wearOs.apk");
                                        Uri uri= FileProvider.getUriForFile(MainActivity.this,"com.example.myapplication"+".provider",file);
                                        Intent i=new Intent(Intent.ACTION_INSTALL_PACKAGE);
                                        i.setDataAndType(uri,"application/vnd.android.package-archive");
                                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        startActivity(i);
                                    }
                                });

                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                Wearable.getChannelClient(getApplicationContext()).close(channel);
                            }
                        }
                    });
                }
            });
        }
    });
}

Если я правильно понял передача файла будет примерно такой

public void onSend(View view) {
    File file = new File("wearOs.apk");
    final String text = file.toString();

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            Collection<String> nodes = getNodes();
            LOGD(TAG, "Nodes: " + nodes.size());
            for (String node : nodes) {
                Task<ChannelClient.Channel> channelTask = Wearable.getChannelClient(getApplicationContext()).openChannel(node, CHANNEL_MSG);
                channelTask.addOnSuccessListener(new OnSuccessListener<ChannelClient.Channel>() {
                    @Override
                    public void onSuccess(ChannelClient.Channel channel) {
                        LOGD(TAG, "onSuccess " + channel.getNodeId());
                        Task<OutputStream> outputStreamTask = Wearable.getChannelClient(getApplicationContext()).getOutputStream(channel);
                        outputStreamTask.addOnSuccessListener(new OnSuccessListener<OutputStream>() {
                            @Override
                            public void onSuccess(OutputStream outputStream) {
                                LOGD(TAG, "output stream onSuccess");
                                try {
                                    InputStream inputStream = getContentResolver().openInputStream(Uri.fromFile(file));
                                    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

                                    byte[] buffer = new byte[1024];

                                    int len;
                                    while ((len = inputStream.read(buffer)) > 0)
                                        byteBuffer.write(buffer, 0, len);

                                    outputStream.write(byteBuffer.toByteArray());
                                    outputStream.flush();
                                    outputStream.close();
                                    inputStream.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            }
        }
    });
}

А как теперь принять этот массив байтов, и запустить установку apk файла на часах?


Ответы (0 шт):