FileDownloader at the android it is showing no errors but the download does not start

前端 未结 1 340
攒了一身酷
攒了一身酷 2020-12-21 23:24

I am trying to download a simple .pdf file I have tried logs but no errors and nothing. I tried to debug but the same till yesterday it worked like charm but no

1条回答
  •  感情败类
    2020-12-21 23:37

    The solution is as below, this should fix your problem. There are changes related to API 28 Android Permissions which made your old code obsolete

    Access Screen

    Output

    Code Snapshot

    AndroidManifest.xml

        
    
    
        
    
    
        
        
    
        
            
                
            
            
                
                    
    
                    
                
            
        
    
    
    

    GenericFileProvider.java

    package com.zackdawood;
    
    import android.support.v4.content.FileProvider;
    
    public class GenericFileProvider extends FileProvider {
    }
    

    FileDownloader.java

    package com.zackdawood;
    
    import android.util.Log;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class FileDownloader {
    
        private static final String TAG = "FileDownloader";
    
        private static final int MEGABYTE = 1024 * 1024;
    
        public static void downloadFile(String fileUrl, File directory) {
            try {
                Log.v(TAG, "downloadFile() invoked ");
                Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
                Log.v(TAG, "downloadFile() directory " + directory);
    
                URL url = new URL(fileUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
    
                InputStream inputStream = urlConnection.getInputStream();
                FileOutputStream fileOutputStream = new FileOutputStream(directory);
                int totalSize = urlConnection.getContentLength();
    
                byte[] buffer = new byte[MEGABYTE];
                int bufferLength = 0;
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, bufferLength);
                }
                fileOutputStream.close();
                Log.v(TAG, "downloadFile() completed ");
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e(TAG, "downloadFile() error" + e.getMessage());
                Log.e(TAG, "downloadFile() error" + e.getStackTrace());
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Log.e(TAG, "downloadFile() error" + e.getMessage());
                Log.e(TAG, "downloadFile() error" + e.getStackTrace());
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "downloadFile() error" + e.getMessage());
                Log.e(TAG, "downloadFile() error" + e.getStackTrace());
            }
        }
    }
    

    MainActivity.java

    package com.zackdawood;
    
    import android.content.ActivityNotFoundException;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.FileProvider;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    import java.io.File;
    import java.io.IOException;
    
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
        private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    
    
        private static boolean hasPermissions(Context context, String... permissions) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
                for (String permission : permissions) {
                    if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                        return false;
                    }
                }
            }
            return true;
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Log.v(TAG, "onCreate() Method invoked ");
    
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
    
        }
    
        public void request(View view) {
    
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);
    
        }
    
        public void view(View view) {
            Log.v(TAG, "view() Method invoked ");
    
            if (!hasPermissions(MainActivity.this, PERMISSIONS)) {
    
                Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
    
                Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
                t.show();
    
            } else {
                File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);  // -> filename = maven.pdf
                File pdfFile = new File(d, "maven.pdf");
    
                Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());
    
                Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", pdfFile);
    
    
                Log.v(TAG, "view() Method path " + path);
    
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                pdfIntent.setDataAndType(path, "application/pdf");
                pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
                try {
                    startActivity(pdfIntent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
                }
            }
            Log.v(TAG, "view() Method completed ");
    
        }
    
        public void download(View view) {
            Log.v(TAG, "download() Method invoked ");
    
            if (!hasPermissions(MainActivity.this, PERMISSIONS)) {
    
                Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");
    
                Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
                t.show();
    
            } else {
                Log.v(TAG, "download() Method HAVE PERMISSIONS ");
    
                //new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
                new DownloadFile().execute("http://www.axmag.com/download/pdfurl-guide.pdf", "maven.pdf");
    
            }
    
            Log.v(TAG, "download() Method completed ");
    
        }
    
        private class DownloadFile extends AsyncTask {
    
            @Override
            protected Void doInBackground(String... strings) {
                Log.v(TAG, "doInBackground() Method invoked ");
    
                String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
                String fileName = strings[1];  // -> maven.pdf
                String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
                File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    
                File pdfFile = new File(folder, fileName);
                Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsolutePath());
                Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsoluteFile());
    
                try {
                    pdfFile.createNewFile();
                    Log.v(TAG, "doInBackground() file created" + pdfFile);
    
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "doInBackground() error" + e.getMessage());
                    Log.e(TAG, "doInBackground() error" + e.getStackTrace());
    
    
                }
                FileDownloader.downloadFile(fileUrl, pdfFile);
                Log.v(TAG, "doInBackground() file download completed");
    
                return null;
            }
        }
    }
    

    strings.xml

    
        DemoInternalDownload
        Settings
        File View
        File Download
        Request Access Again
    
    
    

    external_files.xml

    
    
        
    
    

    network_security_config.xml

    
    
        
            maven.apache.org
            www.axmag.com
        
    
    

    activity_main.xml

    
    
    
        
    
            

    build.gradle

     apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 28
        defaultConfig {
            applicationId "com.zackdawood"
            minSdkVersion 15
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    }
    

    0 讨论(0)
提交回复
热议问题