How to download file/image from url to your android app

五迷三道 提交于 2019-11-28 05:43:30

问题


I need my android app to make request to url to download an image from this url so I have built this class to help me, BUT it didn't work ???

public class MyAsnyc extends AsyncTask<Void, Void, Void> {
public static File file;
InputStream is;

    protected void doInBackground() throws IOException {
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");

        try{
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");

            // Open a connection to that URL.
            URLConnection ucon = url.openConnection();

            // Define InputStreams to read from the URLConnection.
            is = ucon.getInputStream();
        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute() {
        try {
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(
                null,
                new String[] { file.toString() },
                null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                }
            );
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And I have, in the Activity class on onclick(), this function:

public void down(View v) {
    // ImageManager ob=new ImageManager();
    // ob.DownloadFromUrl("");

     new MyAsnyc().execute();
}

Although I have written the permissions in the manfiest.xml

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

回答1:


try this

public class MyAsnyc extends AsyncTask<Void, Void, Void> {
    public static File file;
    InputStream is;

    protected void doInBackground() throws IOException {

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");
        try {    
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            is = ucon.getInputStream();

            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute() {
        try {
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(null,
                    new String[]{file.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}



回答2:


The problem with your code is you have not read the InputStream. You should try this

Bitmap bitmap = BitmapFactory.decodeStream(is); 
return bitmap;

and make the Asynctask return type as Bitmap. Or, As you have used that is in postExecute() your doInBackground() should return that InputStream object is. But you are returning void.

Okey.Try this edited Asynctask.

    private  class MyAsnyc extends  AsyncTask <Void,Void,File> {
    File file;
    @Override 
    protected File doInBackground( Void... params ) { 
        InputStream is = null;
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File( path , "Demo Picture.jpg" ) ;  
        try { // Make sure the Pictures directory exists.path.mkdirs() ; URL url = new URL ( "http: / /androidsaveitem .appspot.com/download.jpg") ; URLConnection ucon = url.openConnection ( ) ; 
            path.mkdirs();

            OutputStream os = new FileOutputStream(file) ; 
            byte [ ] data = new byte [ is.available ( ) ] ;
            is.read ( data ) ; os.write (data );is.close ( ) ; os.close ( ) ; 
            return file;
        }
        catch (Exception e){ 
            Log .d ( "ImageManager " , " Error: " + e ) ;
        }           

        return null;
    }
    protected void onPostExecute (File file) {
        try{
            MediaScannerConnection.scanFile( null , new String [] {file.toString( ) } , null , new MediaScannerConnection.OnScanCompletedListener ( ) { public void onScanCompleted (String path, Uri uri) { 
                Log.i ( " External Storage" , " Scanned " + path + " : " ) ; Log.i ( " E x t e r n a l S t o r a g e " , " - > u r i = " + uri ) ; } } ) ;
        }catch (Exception e) {
            // TODO: handle exception
        }
    }}



回答3:


new DownloadImageFromUrlTask().execute(imagePath);

//add glide dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

public class DownloadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
        String downloadPath = "";

        @Override
        protected Bitmap doInBackground(String... args) {
            try {
                downloadPath = args[0];
                return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
                String root_Path =  Environment.getExternalStorageDirectory().toString();

                String saveImagePath = root_Path + "/" + photoFileName;

                saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
                loadImageWithGlide(MainActivity.this, myImageView, saveImagePath);
            } else {
                myImageView.setImageResource(R.drawable.default_photo);
            }
        }
    }

    public static Boolean saveBitmapToJPEGFile(Context ctx, Bitmap theTempBitmap, File theTargetFile, int i) {
        Boolean result = true;
        if (theTempBitmap != null) {
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(theTargetFile);
                theTempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out);    //kdfsJpegCompressionRatio
            } catch (FileNotFoundException e) {
                result = false;
                e.printStackTrace();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            result = false;
        }
        return result;
    }

    public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
        Glide.with(theCtx)
                .load(theUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(theImageView);

    }



回答4:


Define these on the top side

Button BtnDownload;

DownloadManager downloadManager;

After, You should write on create inside :

BtnDownload = (Button)findViewById(R.id.button1);

Later, You should write to the button's click event

downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

Uri uri = Uri.parse("your url");

DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

Long reference = downloadManager.enqueue(request);

Finally, you need to add this onto the application tag to the manifest.xml :

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


来源:https://stackoverflow.com/questions/9762057/how-to-download-file-image-from-url-to-your-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!