如何以编程方式将图像幻灯片设置为android主屏幕(壁纸)?

时间:2016-09-30 09:28:32

标签: android android-studio wallpaper

我可以通过以下代码设置来自drawable的单个图像作为android主屏幕背景/壁纸

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

我想知道的是如何显示图像幻灯片。更像是图像在特定时间间隔后更改,比如2分钟。考虑到可以并且已经在Google Play商店中提供的几个基于壁纸的应用程序中实现,请与我分享示例代码或链接。

我不打算随时打开应用程序或在后台打开应用程序。我已经在网上做了大量的研究,但我无法找到实例或任何有效的方法来做到这一点。如果这个想法存在任何性能缺陷,我愿意接受建议。

++ 请让我自己清楚,以避免任何混淆。 我能够将特定图像设置为我的设备壁纸(不是我的应用程序中的任何布局或屏幕)。我的要求是不时地改变那个特定的图像,考虑到这个事实,让我说我有十几张图像。

提前致谢

4 个答案:

答案 0 :(得分:1)

首先,您需要导入这个真棒库https://github.com/JakeWharton/ViewPagerIndicator

接下来的步骤很简单,我给你自己的工作代码

你只需根据你的需要复制粘贴和替换。

首先复制这个pojo类

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


}

现在这个适配器:

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

现在这是主要活动

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

            }
        });


    }
}

您可以尝试使用此代码。

答案 1 :(得分:0)

Shyamnath Mallinathan,

将所有图像放入viewpager并禁用viewpager的滑动功能。

实施计时器,每2秒后滑动一次viewpager页面

快乐编码!!

答案 2 :(得分:0)

将您的图片放入viewpager中,然后在您的Activity中创建onCreate加载视图寻呼机的适配器,然后:

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

        }

答案 3 :(得分:0)

我已经死了几个星期才能制作图像序列动态壁纸终于找到了一种方法,你可以控制图片之间的时间,这是一项服务,所以你不需要只是从设置打开你的应用程序 - 显示---动态壁纸 - 图像序列和完成

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

当然不要忘记明显的perimissions