Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android set image as wallpaper

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

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) {
        }
    }

}

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.");
            }

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;
            }
        }

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

}

Conclusion

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);
like image 230
KC Chai Avatar asked Aug 13 '12 16:08

KC Chai


1 Answers

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).

like image 173
rajpara Avatar answered Sep 21 '22 14:09

rajpara