0

我没有错误,但应用程序。什么都不做。

下载器链接http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

package com.androidhive.httprequests;

import java.io.IOException;
import java.net.URL;

import android.util.Log;

import com.androidhive.httprequests.AndroidHTTPRequestsActivity;

public class DownloadFromUrl {

public static void main ()
{
    try {
    AndroidHTTPRequestsActivity hallo = new AndroidHTTPRequestsActivity();
    String imageURL2 = "sample.jpg";
    URL url = new URL("http://api.androidhive.info/images/" + imageURL2);
    String filename2 = String.valueOf(url.hashCode());
    hallo.DownloadFromUrl(imageURL2, filename2);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
}
}
4

1 回答 1

0

基本的下载示例代码应该是这样的:

private class DownloadWallpaperTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        String wallpaperURLStr = params[0];
        String localPath = Integer.toString(wallpaperURLStr.hashCode());
        try {
            URL wallpaperURL = new URL(wallpaperURLStr);
            URLConnection connection = wallpaperURL.openConnection();

            //get file length
            int filesize = connection.getContentLength();
            if(filesize < 0) {
                downloadProgressDialog.setMax(1000000);
            } else {
                downloadProgressDialog.setMax(filesize);
            }

            InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);
            String appName = getResources().getString(R.string.app_name);
            OutputStream outputStream = openFileOutput(localPath, Context.MODE_PRIVATE);
            byte buffer[] = new byte[1024];
            int dataSize;
            int loadedSize = 0;
            while ((dataSize = inputStream.read(buffer)) != -1) {
                loadedSize += dataSize;
                publishProgress(loadedSize);
                outputStream.write(buffer, 0, dataSize);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return localPath;
    }


    protected void onProgressUpdate(Integer... progress) {
        downloadProgressDialog.setProgress(progress[0]);
    }

    protected void onPostExecute(String result) {
        downloadProgressDialog.hide();

        //open preview activity
        Bundle postInfo = new Bundle();
        postInfo.putString("localpath", result);

        if (previewPanelIntent == null) {
            previewPanelIntent = new Intent(MainActivity.this,
                    PreviewPanel.class);
        }

        previewPanelIntent.putExtras(postInfo);
        startActivity(previewPanelIntent);
    }
}

要获取更多信息,我在我的应用程序中使用了一个 android 应用程序源代码:

Android 下载带进度条的图片

于 2014-03-26T10:44:07.297 回答