Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/202.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
NetworkOnmainThreadException android+;Rxjava_Android_Rx Java2 - Fatal编程技术网

NetworkOnmainThreadException android+;Rxjava

NetworkOnmainThreadException android+;Rxjava,android,rx-java2,Android,Rx Java2,我有一个将字节流写入文件并返回文件的代码 但我在将输入流写入文件时遇到networkonmainthreadexception accessTokenValidationWithResponseBodyForPDF(LinkApi.downloadFile(fileUrl)) .flatMap(new Function<ResponseBody, ObservableSource<File>>() {

我有一个将字节流写入文件并返回文件的代码 但我在将输入流写入文件时遇到networkonmainthreadexception

accessTokenValidationWithResponseBodyForPDF(LinkApi.downloadFile(fileUrl))
                .flatMap(new Function<ResponseBody, ObservableSource<File>>() {
                    @Override
                    public ObservableSource<File> apply(@io.reactivex.annotations.NonNull ResponseBody responseBody) throws Exception {
                        return Observable.just(writeResponseBodyToDisk(responseBody))
                                .onErrorReturn(new Function<Throwable, File>() {
                                    @Override
                                    public File apply(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                                        return new File(AppConstants.not_valid);
                                    }
                                });
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<File>() {
                    @Override
                    public void onNext(@NotNull File resultObject) {
                        try {
                            hideProgress();
                            if (resultObject.getPath().equals(AppConstants.not_valid)) {

                                showAlertDialog(getString(R.string.something_went_wrong), true);

                            } else {

                                File pdfFile = (File) resultObject;
                                downloadedFile = pdfFile;
                                if (pdfFile != null) {
                                    displayPdf(pdfFile);
                                }

                            }
                        } catch (Exception e) {
                        }

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        hideProgress();
                        
                    }

                    @Override
                    public void onComplete() {

                    }
                });

这是因为您调用
writeResponseBodyToDisk
,然后将其结果转换为可观察结果。您必须使方法调用本身发生在后台线程上,例如通过

Observable.fromCallable(()->writeResponseBodyToDisk(responseBody))
.subscribeOn(Schedulers.io())
.onErrorReturn(…)

请注意,在原始代码中使用
.subscribeOn(Schedulers.io())
不会进入
flatMap
,因为该函数运行在
AccessTokenValidationWithResponseByForPDF
的发射器线程上。你必须把
subscribebeon
s放在离作品尽可能近的地方,并且经常在许多地方重复它。

谢谢它起作用了。。真的帮助了你的解释,因为我正在学习rxjavaI,我改成了下面的样子,对吗?return Observable.fromCallable(()->writeResponseBodyToDisk(responseBody)).subscribeOn(Schedulers.io()).onerrorrurn({…});}
     private File writeResponseBodyToDisk(ResponseBody body) {

        
        String extStorageDirectory = getApplicationContext().getFilesDir().toString();

        File folder = new File(extStorageDirectory, ".Link");
        if (!folder.exists())
            folder.mkdir();

        SecureRandom secureRandom = new SecureRandom();
        int random = secureRandom.nextInt();

        File futureStudioIconFile = new File(extStorageDirectory + File.separator + ".Link" + File.separator + "link" + random + ".pdf");

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            byte[] fileReader = new byte[4096];

            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(futureStudioIconFile);

            while (true) {
                int read = inputStream.read(fileReader);//going to exception with networkonmainthreadexception

                if (read == -1) {
                    break;
                }

                outputStream.write(fileReader, 0, read);

                fileSizeDownloaded += read;

            }

//                outputStream.flush();

        } catch (Exception e) {

            Log.i("PDF", e.getMessage());
        } finally {
            safeClose(inputStream);
            safeClose(outputStream);
        }


        return futureStudioIconFile;

    }