如何从url下载文件/图像到你的Android应用程序

时间:2012-03-18 20:35:35

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

我需要我的Android应用程序来请求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 个答案:

答案 0 :(得分: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();
        }

    }
}

答案 1 :(得分:0)

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

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

并将Asynctask return类型设为Bitmap。 要么, 正如您在ispostExecute()使用了doInBackground()return应该InputStream is对象void。但是你要回归Asynctask

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

{{1}}

答案 2 :(得分:0)

----试试这个----

在顶部定义这些

按钮BtnDownload;

DownloadManager downloadManager;

之后,你应该写在内部创建:

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

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

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

Uri uri = Uri.parse(“你的网址”);

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

长引用= downloadManager.enqueue(request);

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

“&lt; uses-permission android:name =”android.permission.INTERNET“&gt;&lt; / uses-permission&gt;”

答案 3 :(得分:0)

public string getMerchans(string searchString)
{
    //$query = "SELECT * FROM category c WHERE c.draft=0 ORDER BY c.priority ASC";
    List<merchant> merchants = dbContextIAV.merchants
                                           .Where(c => c.business_name.Contains(searchString))
                                           .OrderBy(c => c.business_name)
                                           .ToList();

    //dbContextIAV.product_merchant.FirstOrDefault().
    var response = new { status = "success", merchants = merchants };

    return JsonConvert.SerializeObject(response, Formatting.None,
           new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
}