1
votes

I'm a beginner in Android development. I'm trying to figure out downloading files with AsyncTask. So far I've been able to bring down HttpUrlConnection and InputStream but I couldn't find anything about downloading the file from the URL. As I said, I am very new in this. Much of the code is from my own personal knowledge. I got the code for Http connection and input stream from an article. I would like to know the next step.

public class MainActivity extends AppCompatActivity {
    Button downloadPDF;
    DownloadingClass downPDF;
    private static final String TAG = "omar.asynctaskdemo;";
    String urlExample = "https://doc.lagout.org/programmation/Actionscript%20-%20Flash%20-%20Flex%20-%20Air/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29.pdf";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadPDF = findViewById(R.id.download_pdf);
        downPDF = new DownloadingClass();

        downloadPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downPDF.execute();
            }
        });

        permissionCheck();
    }

    private void permissionCheck() {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                return;
            }
        }
    }

    private class DownloadingClass extends AsyncTask<String, Integer, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            URL url;
            try {
                url = new URL(urlExample);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                InputStream inputStream = httpURLConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = bufferedReader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
1

1 Answers

1
votes

You can try creating a FileOutputStream, and writing the bytes from the InputStream to the file.

Take a look at FileOutputStream,and its "write(byte[] b)" method. https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html