Android从URL下载图像

Android从URL下载图像,android,Android,我试图创建一个应用程序,从url下载一个图像,然后保存它,但它不工作,我得到两个错误祝酒词显示。我对Java中的html命令不是很在行,但是是的 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.

我试图创建一个应用程序,从url下载一个图像,然后保存它,但它不工作,我得到两个错误祝酒词显示。我对Java中的html命令不是很在行,但是是的

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Button button= (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final EditText inputurl = new EditText(MainActivity.this);
            String urlcode = inputurl.getText().toString();
            boolean success = (new File("/sdcard/backgroundchanger")).mkdir();
            if (!success) {
                Log.w("directory not created", "directory not created");
                Toast.makeText(getApplicationContext(), "ERROR!!", Toast.LENGTH_SHORT).show();
            }

            try {
                URL url = new URL(urlcode);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                String data1 = String.valueOf(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));

                FileOutputStream stream = new FileOutputStream(data1);

                ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outstream);
                byte[] byteArray = outstream.toByteArray();

                stream.write(byteArray);
                stream.close();

                Toast.makeText(getApplicationContext(), "Downloading Completed", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "ERROR!!!", Toast.LENGTH_SHORT).show();
            }
        }
    });

    };

使用以下代码从URL保存图像:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class SaveWallpaperAsync extends AsyncTask<String, String, String> {
    private Context context;
    private ProgressDialog pDialog;
    String image_url;
    URL ImageUrl;
    String myFileUrl1;
    Bitmap bmImg = null;

    public SaveWallpaperAsync(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

        super.onPreExecute();

        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub

        InputStream is = null;

        try {

            ImageUrl = new URL(args[0]);
            // myFileUrl1 = args[0];

            HttpURLConnection conn = (HttpURLConnection) ImageUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Config.RGB_565;
            bmImg = BitmapFactory.decodeStream(is, null, options);

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

        try {

            String path = ImageUrl.getPath();
            String idStr = path.substring(path.lastIndexOf('/') + 1);
            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File(filepath.getAbsolutePath()
                    + "/Wallpapers/");
            dir.mkdirs();
            String fileName = idStr;
            File file = new File(dir, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            bmImg.compress(CompressFormat.JPEG, 75, fos);
            fos.flush();
            fos.close();

            File imageFile = file;
            MediaScannerConnection.scanFile(context,
                    new String[] { imageFile.getPath() },
                    new String[] { "image/jpeg" }, null);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(String args) {
        // TODO Auto-generated method stub

        if (bmImg == null) {

            Toast.makeText(context, "Image still loading...",
                    Toast.LENGTH_SHORT).show();

            pDialog.dismiss();

        }

        else {

            if (pDialog!=null) {
                if (pDialog.isShowing()) {
                    pDialog.dismiss();       
                }
            }

            Toast.makeText(context, "Wallpaper Successfully Saved",
                    Toast.LENGTH_SHORT).show();

        }
    }

}

使用毕加索,它将节省您的时间和内存。您可以确保在清单中添加了此权限。好的,谢谢,我会帮你调查一下的