安卓 - 从网络服务器保存图片并设置为壁纸

3

请问有人可以给我一些关于如何从Web服务器上保存图片并将其设置为壁纸的想法/指导吗?我正在开发一个需要这样做的Android应用程序,但我是新手。非常感谢。

我已经尝试编写自己的代码,但由于下载后找不到我的图片,所以它无法正常工作,但壁纸已经更改为下载的图片。这是我的现有代码。

Bitmap bmImg;

void downloadFile(String fileUrl) {
    URL myFileUrl = null;
    try {
        myFileUrl = new URL(fileUrl);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl
                .openConnection();
        conn.setDoInput(true);
        conn.connect();
        int length = conn.getContentLength();

        InputStream is = conn.getInputStream();

        bmImg = BitmapFactory.decodeStream(is);
        // this.imView.setImageBitmap(bmImg);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        String filepath=Environment.getExternalStorageDirectory().getAbsolutePath(); 
        FileOutputStream fos = new FileOutputStream(filepath + "/" + "output.jpg"); 
        bmImg.compress(CompressFormat.JPEG, 75, fos);
        fos.flush();
        fos.close();

        Context context = this.getBaseContext();
        context.setWallpaper(bmImg);
    } catch (Exception e) {
        //Log.e("MyLog", e.toString());
        TextView tv = (TextView) findViewById(R.id.txt_name);
        tv.setText(e.toString());
    }

}
1个回答

2
我曾尝试编写自己的代码,但由于下载后找不到我的图像,所以它无法正常工作。以下是我现有的代码。
您的代码将保存图像在手机的 data/data/<your_app_package_name> 文件夹中。然后,您可以使用 WallpaperManager实例 或执行context.setWallpaper(bitmap)(已弃用)将位图设置为壁纸。

我想把图片存储在SD卡中。 - Lynnooi
看起来你改了一些代码:现在应该会将图像保存在Sdcard上。并且,将其设置为壁纸。你有收到任何错误吗? - Samuh
是的,我对我的代码进行了一些更改。我没有收到任何错误信息,但我仍然无法在手机中找到图像。不过,壁纸已经成功设置了。 - Lynnooi
嗨,Samuh,只是想告诉你我已经把它存到SD卡上了。非常感谢你的及时回答。 - Lynnooi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接