0

I am able to set an individual image from the drawable as android home screen background/wallpaper via code as shown below

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

What I want to know is how to show a slideshow of images. More like image gets changed after a particular time interval,say 2 minutes. Considering the fact that it is possible and already implemented in several Wallpaper based apps available on Google Play Store, kindly share with me sample code or links.

I do not intend to keep the app open or in the background at all times. I've done a fair amount of research online but I am not able to find examples or any efficient methods to do this. If there is any performance flaw to the idea I am open to suggestions.

++ Please let me make myself clear to avoid any confusion. I am able to set a particular image as my device wallpaper(not any layout or screen within my application). My requirement is to change that particular image from time to time considering the fact, Let's say I have dozen of images.

Thanks in advance

4 Answers4

0

First you need to import this awesome library https://github.com/JakeWharton/ViewPagerIndicator

Next steps are very simple i'm giving you my own working code

you just need to copy paste and replace according to you.

First copy this pojo class

public class Banner {

    private String str_id;
    private String str_photo;

    Banner() {

    }

    public Banner(String str_id, String str_photo) {
        this.str_id = str_id;
        this.str_photo = str_photo;
    }

    public String getStr_id() {
        return str_id;
    }

    public void setStr_id(String str_id) {
        this.str_id = str_id;
    }

    public String getStr_photo() {
        return str_photo;
    }

    public void setStr_photo(String str_photo) {
        this.str_photo = str_photo;
    }


}

Now this adapter:

public class SlidingImage_Adapter extends PagerAdapter {

    private List<Banner> IMAGES = new ArrayList<Banner>();
    private LayoutInflater inflater;
    private Context context;
    private Typeface typefaceReguler, typefaceLight, typefaceItalic;

    public SlidingImage_Adapter(Context context, List<Banner> IMAGES) {
        this.context = context;
        this.IMAGES = IMAGES;
        inflater = LayoutInflater.from(context);
        System.out.println("----imagesssss----- "+IMAGES);
       /* typefaceReguler = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular_0.ttf");
        typefaceLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light_0.ttf");
        typefaceItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic_0.ttf");*/
    }

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

    @Override
    public int getCount() {
        return IMAGES.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);

        Banner banner = IMAGES.get(position);
        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
        final ImageView img_browse = (ImageView) imageLayout.findViewById(R.id.imageView_Browse);
        final TextView textView = (TextView) imageLayout.findViewById(R.id.textView_collectiontitle);
//        textView.setTypeface(typefaceReguler);
//        textView.setTextSize(AppController.textSize(context, 30));
//        textView.setTextColor(ContextCompat.getColor(context, R.color.white));
//        int width = imageView.getLayoutParams().width = AppController.screenWidth(context) / 1;
//        int height = imageView.getLayoutParams().height = AppController.screenHeight(context) / 3;

        img_browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "Browse Collection", Toast.LENGTH_SHORT).show();
            }
        });

        if (position == 0) {
            textView.setText("woodland original");


        }
        if (position == 1) {
            textView.setText("nike original");
        }
        if (position == 2) {
            textView.setText("rebook original");
        }
        if (position == 3) {
            textView.setText("adidas original");
        }
        if (!banner.getStr_photo().isEmpty())
        {
            System.out.println("---Working---- "+banner.getStr_photo());
            Picasso.with(context)
                    .load("Your image here")
                    .placeholder(R.drawable.banner_shoe)   // optional
                    .error(R.drawable.banner_shoe)      // optional
                    .resize(250, 200)                        // optional
                    .rotate(90)                             // optional
                    .into(imageView);
        }
        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;
    }
}

Now this is the Main Activity

public class SlideAutomaticWithViewPager extends AppCompatActivity {
    public List<Banner> list_banner = new ArrayList<Banner>();
    private SlidingImage_Adapter slidingImage_adapter;
    private static ViewPager mPager;
    private static int NUM_PAGES = 0;
    private static int currentPage = 0;

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

        list_banner.add(new Banner("1", "Your image link here"));
        list_banner.add(new Banner("2", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png"));
        list_banner.add(new Banner("3", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png"));
        list_banner.add(new Banner("4", "https://www.simplifiedcoding.net/wp-content/uploads/2015/10/advertise.png"));

        mPager = (ViewPager) findViewById(R.id.viewpagerHome);
        slidingImage_adapter = new SlidingImage_Adapter(this, list_banner);
        mPager.setAdapter(slidingImage_adapter);

        CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);

        indicator.setViewPager(mPager);

        final float density = getResources().getDisplayMetrics().density;

        indicator.setRadius(5 * density);

        NUM_PAGES = list_banner.size();


        // Auto start of viewpager
        final Handler handler = new Handler();
        final Runnable Update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                mPager.setCurrentItem(currentPage++, true);
            }
        };
        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(Update);
            }
        }, 3000, 3000);

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });


    }
}

You can try this code.

Däñish Shärmà
  • 2,891
  • 2
  • 25
  • 43
  • Hi Danish, I appreciate your willingness to help. But my question if looked upon clearly states that my requirement is to set a slideshow of images as my device wallpaper(android home screen). Not my application screen but my device screen. Kindly help. Thanks in advance. – Shyamnath Mallinathan Oct 01 '16 at 10:55
  • wish someone knew i have task and can't find single example or tutorial for wallpaper changes images :( –  Oct 20 '16 at 08:58
0

hi Shyamnath Mallinathan,

Put all images in the viewpager and disable swipe functionality of viewpager.

Implement a timer to slide viewpager pages after every 2 seconds

Happy Coding!!

Mohit Trivedi
  • 699
  • 3
  • 13
  • Hi mohit, I asked about setting the image to my device screen(android home screen) not a layout within the application screen. In that case the application might not be even running all the time. – Shyamnath Mallinathan Oct 01 '16 at 11:05
0

Put your images in a viewpager and then in your Activity's onCreate load the view pager's adapter and then :

Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < mAdapter.getCount()-1; i++) {
                        final int value = i;
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mPager.setCurrentItem(value, true);
                            }
                        });
                    }
                }
            };
            new Thread(runnable).start();

        }
nishith kumar
  • 981
  • 7
  • 20
  • Hi n9153, I guess you are still unclear about my question. My apologies. My requirement is to set the image to the device home screen ,not within the application. It should change from time to time. – Shyamnath Mallinathan Oct 01 '16 at 11:07
0

I'm Dead for weeks to make image sequence live wallpaper finally found a way and you can control with the time between the pictures and it is a service so u don't need to open your app just from settings -- display--- live wallpaper -- image sequence and done

public class MainActivity extends WallpaperService {

@Override
public Engine onCreateEngine() {
    return new WallpaperEngine();
}

class WallpaperEngine extends Engine {
    //Duration between slides in milliseconds
    private final int SLIDE_DURATION = 2000;

    private int[] mImagesArray;
    private int mImagesArrayIndex = 0;
    private Thread mDrawWallpaper;
   // private String mImageScale = "Fit to screen";
    private CustomWallpaperHelper customWallpaperHelper;

    public WallpaperEngine() {
        customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
        mImagesArray = new int[] {R.drawable.garden1,R.drawable.garden2,R.drawable.garden3,R.drawable.garden4,R.drawable.girl1,
                R.drawable.girl2,R.drawable.greenww,R.drawable.sports1,R.drawable.sports2,R.drawable.sports3,R.drawable.sports4};

        mDrawWallpaper = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        drawFrame();
                        incrementCounter();
                        Thread.sleep(SLIDE_DURATION);
                    }
                } catch (Exception e) {
                    //
                }
            }
        });

        mDrawWallpaper.start();
    }

    private void incrementCounter() {
        mImagesArrayIndex++;

        if (mImagesArrayIndex >= mImagesArray.length) {
            mImagesArrayIndex = 0;
        }
    }

    private void drawFrame() {
        final SurfaceHolder holder = getSurfaceHolder();

        Canvas canvas = null;

        try {
            canvas = holder.lockCanvas();

            if (canvas != null) {
                drawImage(canvas);
            }
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }

    private void drawImage(Canvas canvas)
    {

        Bitmap image = BitmapFactory.decodeResource(getResources(),
                mImagesArray[mImagesArrayIndex]);
        Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
        canvas.drawBitmap(b, 0,0, null);
    }

CustomWallpaperHelper

public class CustomWallpaperHelper {
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to   screen";

public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen";

private Context mContext;
private Resources mResources;

private Point screenSize = new Point();

private Bitmap bgImageScaled;
private Point bgImagePos = new Point(0, 0);

public CustomWallpaperHelper(Context mContext, Resources mResources) {
    this.mContext = mContext;
    this.mResources = mResources;

    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    screenSize.x = display.getWidth();
    screenSize.y = display.getHeight();

    ;
}

private void scaleBackground() {
    String imageScale = "Stretch to screen";
    Bitmap bgImage = null;

    if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
        bgImagePos = new Point(0, 0);
        bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true);
    }
}

public void setBackground(Canvas canvas) {
    if (bgImageScaled != null) {
        canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null);
    } else {
        canvas.drawColor(0xff000000);
    }
}

public int getScreenWidth() {
    return screenSize.x;
}

public int getScreenHeight() {
    return screenSize.y;
}

public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) {
    Point imagePos = new Point();

    imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x)) / 2;
    imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y)) / 2;

    return imagePos;
}

public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) {
    PointF canvasScale = new PointF(1f, 1f);

    if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
        canvasScale.x = getScreenWidth() / (1f * imageWidth);
        canvasScale.y = getScreenHeight() / (1f * imageHeight);
    } else {
        boolean tooWide = false;
        boolean tooTall = false;

        if (getScreenWidth() < imageWidth) {
            tooWide = true;
        }

        if (getScreenHeight() < imageHeight) {
            tooTall = true;
        }

        if (tooWide && tooTall) {
            int x = imageWidth / getScreenWidth();
            int y = imageHeight / getScreenHeight();

            if (x > y) {
                canvasScale.x = getScreenWidth() / (1f * imageWidth);
                canvasScale.y = 1;
            } else {
                canvasScale.x = 1;
                canvasScale.y = getScreenHeight() / (1f * imageHeight);
            }
        } else if (tooWide) {
            canvasScale.x = getScreenWidth() / (1f * imageWidth);
            canvasScale.y = 1;
        } else if (tooTall) {
            canvasScale.x = 1;
            canvasScale.y = getScreenHeight() / (1f * imageHeight);
        }
    }

    return canvasScale;
}

of course don't forget the manifest perimissions