本文介绍了Android设置图片为墙纸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please show me an example code on how to set image as wallpaper using Android WallpaperManager. I have shortened and edited my question. Hopefully you guys could understand my question. I will show some attempts I have made.

HomeActivity.class

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

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 无法解析为变量")

1st Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")

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 无法解析为变量")

2nd Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")

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 获取图像.

3rd Attempt (My setResource(R.id.pager) is not getting the image from the 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 上方,我的整个项目将无法运行.

If i put the below codes above my onCreate my whole project will not run.

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

推荐答案

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

Try below code in ImagePagerActivity, i tested below code and it is working.

    // 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();
    }
}

它将设置当前可见分页器的项目视图(如果是进度轮或图像).

It will set current visible pager's item view(if it is progress wheel or image).

这篇关于Android设置图片为墙纸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 06:03