【问题标题】:How to set a slideshow of images as android home screen(wallpaper) programmatically?如何以编程方式将图像幻灯片设置为 android 主屏幕(壁纸)?
【发布时间】:2016-09-30 09:28:32
【问题描述】:

我可以通过如下所示的代码将可绘制对象中的单个图像设置为 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 商店上的几个基于壁纸的应用程序中实现,请与我分享示例代码或链接。

我不打算让应用程序始终处于打开状态或在后台运行。我已经在网上进行了大量研究,但我找不到示例或任何有效的方法来做到这一点。如果这个想法有任何性能缺陷,我愿意接受建议。

++ 请让我说清楚,以免造成任何混淆。 我可以将特定图像设置为我的设备壁纸(不是我的应用程序中的任何布局或屏幕)。考虑到事实,我的要求是不时更改该特定图像,假设我有十几个图像。

提前致谢

【问题讨论】:

    标签: android android-studio wallpaper


    【解决方案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) {
    
                }
            });
    
    
        }
    }
    

    你可以试试这个代码。

    【讨论】:

    • 您好丹麦人,感谢您愿意提供帮助。但是我的问题是否清楚地表明我的要求是将图像幻灯片设置为我的设备壁纸(android 主屏幕)。不是我的应用程序屏幕,而是我的设备屏幕。请帮忙。提前致谢。
    • 希望有人知道我有任务并且找不到壁纸更改图像的单个示例或教程:(
    【解决方案2】:

    嗨,Shyamnath Mallinathan,

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

    实现一个计时器,每 2 秒滑动一次 viewpager 页面

    编码愉快!!

    【讨论】:

    • 嗨 mohit,我询问了关于将图像设置到我的设备屏幕(android 主屏幕)而不是应用程序屏幕中的布局。在这种情况下,应用程序甚至可能不会一直运行。
    【解决方案3】:

    将您的图像放入 viewpager,然后在 Activity 的 onCreate 中加载 view pager 的适配器,然后:

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

    【讨论】:

    • 您好 n9153,我想您仍然不清楚我的问题。我很抱歉。我的要求是将图像设置为设备主屏幕,而不是在应用程序中。它应该不时改变。
    【解决方案4】:

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

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

    自定义壁纸助手

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

    当然不要忘记清单权限

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多