【问题标题】:How to download file/image from url to your android app如何从 url 下载文件/图像到您的 android 应用程序
【发布时间】:2012-04-03 11:01:39
【问题描述】:

我需要我的 android 应用程序向 url 发出请求以从该 url 下载图像 所以我建立了这个类来帮助我,但是它没有用???

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();
        }
    }
}

我在 onclick() 的 Activity 类中有这个函数:

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

     new MyAsnyc().execute();
}

虽然我在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" />

【问题讨论】:

标签: android download android-networking android-notification-bar


【解决方案1】:

试试这个

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();
        }

    }
}

【讨论】:

  • 你对旧的做了什么修改?
  • 查看此日志“03-18 23:28:24.611: D/ImageManager(332): Error: java.io.FileNotFoundException: /mnt/sdcard/Pictures/DemoPicture.jpg (Permission denied) "
  • 图片损坏了,为什么会这样?
【解决方案2】:

在顶部定义这些

Button BtnDownload;

DownloadManager downloadManager;

之后,你应该在create里面写:

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

稍后,您应该写入按钮的点击事件

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);

最后,您需要将它添加到 manifest.xml 的应用程序标签中:

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

【讨论】:

  • 请确保您将代码块用于代码示例
  • 欢迎来到 StackOverflow:如果您发布代码、XML 或数据示例,请在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码示例”按钮 ( { } ) 或使用 Ctrl键盘上的 +K 可以很好地格式化和语法突出显示它!
【解决方案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】:

    您的代码的问题是您还没有阅读InputStream。 你应该试试这个

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

    并将Asynctask return 类型设为Bitmap。 要么, 正如您在postExecute() 中使用了is 一样,您的doInBackground() 应该returnInputStream 对象is。但是你正在返回void

    Okey。试试这个编辑过的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
            }
        }}
    

    【讨论】:

    • 我不明白你的意思?
    • 尝试Asynctask的第三个参数为InputStream,返回来自doinbackground
    • 你能用你告诉我的东西来修改这段代码吗?因为我很困惑!
    • 查看日志":: 03-18 23:28:24.611: D/ImageManager(332): Error: java.io.FileNotFoundException: /mnt/sdcard/Pictures/DemoPicture.jpg (Permission拒绝)
    • 请让单词出现分开的字母,所以我看不懂代码你能看到吗??
    猜你喜欢
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2020-09-12
    • 2018-03-05
    • 2020-03-08
    相关资源
    最近更新 更多