anr向可穿戴设备发送大文件

osh3o9ms  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(226)

考虑到使用channelclient类将文件从手机发送到可穿戴设备的文档很少,我已经让它开始工作了。但是,在发送较大的文件时,我遇到了一个anr错误。我用的是一个 Foreground Service 处理上传,我认为这是为了长期运行的任务。奇怪的是,anr正在全球范围内发生 Activity 用户在其中选择要上载的文件。
服务

public class UploadFile extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        createForegroundNotification();

        Uri fileUri = Uri.parse(intent.getExtras().getString("file"));
        String fileName = getFileName(fileUri);

        List<Node> nodes = Utilities.getNodesAsync();

        for (Node node : nodes) {
          ChannelClient channelClient = Wearable.getChannelClient(context);

                channelClient.openChannel(node.getId(), fileName).addOnSuccessListener(channel -> {

                Task<OutputStream> outputStreamTask = channelClient.getOutputStream(channel);

                outputStreamTask.addOnSuccessListener(outputStream -> {

                    try {
                        InputStream inputStream = context.getContentResolver().openInputStream(fileUri);
                        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();
                    } finally {
                        stopForeground(true);
                    }

                });
            });
        }   
    }
}

useraddactivity:

mFileUploadButton.setOnClickListener(view -> mFileUpload.launch("*/*"));

final ActivityResultLauncher<String> mFileUpload = registerForActivityResult(new ActivityResultContracts.GetContent(),
    uri -> {

        final Intent serviceIntent = new Intent(this, UploadFile.class);
        final Bundle extrasService = new Bundle();
        extrasService.putString("file", uri.toString());
        serviceIntent.putExtras(extrasService);

        ContextCompat.startForegroundService(this, serviceIntent);

    });

错误:

2021-07-26 09:26:56.391 1558-13178/? E/ActivityManager: ANR in com.my.app (com.my.app/.Activities.UserAddActivity)
PID: 13090
Reason: Input dispatching timed out (1c8d463 com.my.app/com.my.app.Activities.UserAddActivity (server) is not responding. Waited 5003ms for FocusEvent(hasFocus=false))
Parent: com.my.app/.Activities.UserAddActivity

anr仅适用于大型文件。我正在测试的是63mb。奇怪的是,这个文件确实传输到了可穿戴设备上,但手机在完成之前抛出了一个anr。
我甚至尝试过将代码放入数据库中的异步任务中 Service .

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题