web-dev-qa-db-ja.com

AsyncTaskでファイルをダウンロードする

私はasyncTaskでファイルをダウンロードしようとしていますが、機能していません、エラーメッセージも何もありません、ファイルをダウンロードしないでください...私はすべてを試しますが、しばらくの間入っていないようです...問題になりますか?私は自分の携帯電話でテストしました、URLも大丈夫です。

class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Starting download");
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(f_url[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file

            OutputStream output = new         FileOutputStream(root+"/downloadedfile.jpg");
            byte data[] = new byte[1024];

            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;

                // writing data to file
                output.write(data, 0, count);

            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }



    /**
     * After completing background task
     * **/
    @Override
    protected void onPostExecute(String file_url) {
       System.out.println("Downloaded");
    }

}
8
Matheus Weber

私はあなたのコードを実行しました、そしてそれは私にとってうまくいきます。画像がSDカードにダウンロードされました。

注意点として、AndroidManifest.xmlで次の権限が設定されていることを確認してください。

<uses-permission Android:name="Android.permission.INTERNET" />

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />

ここに私が得たログがあります(ProgressDialogを追加したことに注意してください):

03-21 16:53:46.422  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:53:56.211  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Starting download
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ checkMirrorLinkEnabled returns : false
03-21 16:54:06.441  21017-21017/com.imagedownload.danielnugent.imagedownload D/Dialog﹕ showing allowed
03-21 16:54:06.461  21017-25126/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloading
03-21 16:54:06.461  21017-21017/com.imagedownload.danielnugent.imagedownload D/Activity﹕ #1 setTransGradationModeColor false
03-21 16:54:06.481  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: left = 0
03-21 16:54:06.481  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: top = 0
03-21 16:54:06.491  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: right = 144
03-21 16:54:06.491  21017-21017/com.imagedownload.danielnugent.imagedownload D/ProgressBar﹕ updateDrawableBounds: bottom = 144
03-21 16:54:11.596  21017-21017/com.imagedownload.danielnugent.imagedownload I/System.out﹕ Downloaded

これが役に立つ場合に備えて、ここで私のために働いた完全なMainActivity.Javaコードを示します。 (urlはプレースホルダーです):

import Android.app.ProgressDialog;
import Android.os.AsyncTask;
import Android.os.Environment;
import Android.support.v7.app.ActionBarActivity;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.Menu;
import Android.view.MenuItem;

import Java.io.BufferedInputStream;
import Java.io.FileOutputStream;
import Java.io.InputStream;
import Java.io.OutputStream;
import Java.net.URL;
import Java.net.URLConnection;


public class MainActivity extends ActionBarActivity {

    private ProgressDialog pDialog;

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

        new DownloadFileFromURL().execute("http://www.example.com/IMG.jpg");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            System.out.println("Starting download");

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading... Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                String root = Environment.getExternalStorageDirectory().toString();

                System.out.println("Downloading");
                URL url = new URL(f_url[0]);

                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file

                OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
                byte data[] = new byte[1024];

                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;

                    // writing data to file
                    output.write(data, 0, count);

                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }



        /**
         * After completing background task
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            System.out.println("Downloaded");

            pDialog.dismiss();
        }

    }

}
10
Daniel Nugent