2

我需要我的 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" />
4

4 回答 4

2

尝试这个

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

    }
}
于 2012-03-18T20:58:01.500 回答
2

在顶部定义这些

Button BtnDownload;

DownloadManager downloadManager;

之后,您应该在 create inside 上写:

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"/> 
于 2018-03-28T11:59:16.467 回答
1
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);

    }
于 2018-03-28T12:26:46.923 回答
-1

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

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

并将Asynctask return类型设为Bitmap. 或者,正如您ispostExecute()您的doInBackground()should returnthat InputStreamobject中使用的那样is。但你要回来了void

好的。试试这个编辑过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
        }
    }}
于 2012-03-18T20:54:14.970 回答