@Chesterfield25

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

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

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

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();
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    }


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

try {
                                File file = new File("wearOs.apk");

                                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();

                                    try (FileOutputStream fileOuputStream = new FileOutputStream("wearOs.apk")){
                                        fileOuputStream.write(byteArray);
                                    }

                                }
                                Log.d(TAG, "reading: " + file);
                                final File finalFile = file;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Intent(Intent.ACTION_INSTALL_PACKAGE).putExtra("wearOs.apk", finalFile);
                                    }
                                });

                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                Wearable.getChannelClient(getApplicationContext()).close(channel);
                            }
  • Вопрос задан
  • 100 просмотров
Пригласить эксперта
Ответы на вопрос 2
xez
@xez Куратор тега Java
TL Junior Roo
Примите «текст», сохраните в файл.
Ответ написан
@freedom1b2830
InputStream inputStream=вашесоединение;
FileOutputStream fos=new FileOutputStream(new File("outputFile"));
while (inputStream. available()>0){
     byte[] buffer=new byte[8192];//буфер
     int readedLen= inputStream.read(buffer);//читаем байты в буфер, получаем объем прочитаного в readedLen
     fos.write(buffer, 0, readedLen);
     fos.flush();
}
//чтобы избавиться от не красивых вызовов .close() и утечек ресурсов в java8+ прочитайте про try-with-resources
fos.close();
inputStream.close();
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы