6

请向我展示如何使用 Android WallpaperManager 将图像设置为墙纸的示例代码。我已经缩短并编辑了我的问题。希望你们能理解我的问题。我将展示我所做的一些尝试。

HomeActivity.class

public class HomeActivity extends BaseActivity {

    String[] imageUrls;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_home);
        ArrayList<String> url = new ArrayList<String>();
        try {
            URL url_link = new URL("http://mywebsite.net/web/thumb.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url_link.openStream()));
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("list");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                Element fstElmnt = (Element)node;
                NodeList nameList = fstElmnt.getElementsByTagName("thumb_url");
                Element nameElement = (Element)nameList.item(0);
                nameList = nameElement.getChildNodes();

                url.add(nameList.item(0).getNodeValue());
            }
            imageUrls = (String[]) url.toArray(new String[0]);
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

    }
    public void onImageGridClick(View view) {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(Extra.IMAGES, imageUrls); 
        startActivity(intent);
    }

    public void onImagePagerClick(View view) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(Extra.IMAGES, imageUrls);
        startActivity(intent);
    }
}

ImagePagerActivity.class

package com.nostra13.example.universalimageloader;


import java.io.IOException;


import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;


public class ImagePagerActivity extends BaseActivity {

    private ViewPager pager;

    private DisplayImageOptions options;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ac_image_pager);
        Bundle bundle = getIntent().getExtras();
        String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
        int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);

        options = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheOnDisc()
            .imageScaleType(ImageScaleType.EXACT)
            .build();

        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(new ImagePagerAdapter(imageUrls));
        pager.setCurrentItem(pagerPosition);
    }

    public void setWallpaper() {

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        try {
         myWallpaperManager.setResource(R.id.pager); // nothing happened 
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_clear_memory_cache:
                imageLoader.clearMemoryCache();
                return true;
            case R.id.item_clear_disc_cache:
                setWallpaper();
                return true;
            default:
                return false;
        }
    }


    @Override
    protected void onStop() {
        imageLoader.stop();
        super.onStop();
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private String[] images;
        private LayoutInflater inflater;

        ImagePagerAdapter(String[] images) {
            this.images = images;
            inflater = getLayoutInflater();
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return images.length;
        }

        @Override
        public Object instantiateItem(View view, int position) {
            final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
            final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

            imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
                public void onLoadingStarted() {
                    spinner.setVisibility(View.VISIBLE);
                }

                public void onLoadingFailed(FailReason failReason) {
                    String message = null;
                    switch (failReason) {
                        case IO_ERROR:
                            message = "Input/Output error";
                            break;
                        case OUT_OF_MEMORY:
                            message = "Out Of Memory error";
                            break;
                        case UNKNOWN:
                            message = "Unknown error";
                            break;
                    }
                    Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();

                    spinner.setVisibility(View.GONE);
                    imageView.setImageResource(android.R.drawable.ic_delete);
                }

                public void onLoadingComplete(Bitmap loadedImage) {
                    spinner.setVisibility(View.GONE);
                    Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
                    imageView.setAnimation(anim);
                    anim.start();
                }

                public void onLoadingCancelled() {
                    // Do nothing
                }
            });

            ((ViewPager) view).addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }

}

第一次尝试(我pagerPosition给出错误“pagerPosition 无法解析为变量”)

public void setWallpaper(){
             Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
    try {
         ImagePagerActivity.this.setWallpaper(bitmap);
            } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        Log.d("Gallery Example", "Image setted.");
            }

第二次尝试(我的 pagerPosition 给出错误“pagerPosition 无法解析为变量”)

public void setWallpaper() {

        try {
            File file = new File("/sdcard/sampleimage");
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
            bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
            Context context = this.getBaseContext();
            context.setWallpaper(bitmap);            
            Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }         
    }

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.set_wallpaper:
                    setWallpaper();
                    return true;
                default:
                    return false;
            }
        }

第三次尝试(我的 setResource(R.id.pager) 没有从 viewpager 获取图像。

public void setWallpaper() {

        WallpaperManager myWallpaperManager
         = WallpaperManager.getInstance(getApplicationContext());
        try {
         myWallpaperManager.setResource(R.id.pager);
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }

}

结论

如果我将以下代码放在我onCreate的整个项目之上,我将无法运行。

        Bundle bundle = getIntent().getExtras();
        String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
        final int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
4

2 回答 2

8

在 ImagePagerActivity 中尝试下面的代码,我测试了下面的代码并且它正在工作。

    // fetch bitmap from view
public static Bitmap getBitmapFromView(View view) {
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        // if we unable to get background drawable then we will set white color as wallpaper
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

public void setWall(int i) {
    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    try {
        // below line of code will set your current visible pager item to wallpaper
        // first we have to fetch bitmap from visible view and then we can pass it to wallpaper
        myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));

        // below line of code will set input stream data directly to wallpaper
        // myWallpaperManager.setStream(InputStream Data);

        // below line of code will set any image which is in the drawable folder 
        // myWallpaperManager.setResource(R.drawable.icon);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

它将设置当前可见寻呼机的项目视图(如果是进度轮或图像)。

于 2012-08-16T17:46:02.373 回答
0

这可能会帮助您使用 setbackground 方法...

String imagePath = ""; // YOUR PATH HERE
FileInputStream is = new FileInputStream(new File(imagePath));
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap b = BitmapFactory.decodeStream(bis);
Bitmap bitmapToUse = Bitmap.createScaledBitmap(b, parent.getWidth(), parent.getHeight(), true);
b.recycle();

if(!("").equals(imagePath)){
    WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
    Drawable wallpaperDrawable = wallpaperManager.getDrawable();
    wallpaperManager.setBitmap(bitmapToUse);
}

那应该将您的文件设置为墙纸没问题。

您能否更具体地说明“saveImage()”需要什么?你想从哪里拯救?是本地存储吗?还是网站?请提供更多详细信息。

[编辑] 为清晰起见更新了代码

[编辑 2] 从 URL 保存图像...

File imageFile = new File("image.png"); // This is location AND file name, all i put here was the filename
URL url = new URL("http://www.whatever.com/image.png");

                    Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
                            .getInputStream());

                    FileOutputStream out = new FileOutputStream(imageFile);
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, out);

[编辑 3]

“父”是您的父视图(通常是当前活动的视图)。还有其他设置方法, parent.width/height 是您将如何定义墙纸图像需要多大的方式。

于 2012-08-13T16:20:48.733 回答