如何使用代码在Android中设置墙纸? [英] How can I set Wallpaper in android using code?

查看:112
本文介绍了如何使用代码在Android中设置墙纸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,该应用程序显示来自服务器的不同照片,并且用户可以将所选照片设置为其设备的墙纸,我使用给定的代码设置了墙纸的工作状态,但是图像未正确设置,因此不适合屏幕.我使用了这段代码.

I am developing an application that shows the different photos from server and user can set selected photos as wallpaper of its device i used given code to set wallpaper it working but image was not set properly it not fit to screen. I used this code.

            String dirPath = getFilesDir().toString();

        String folder = mPhotos.get(nextPosition - 1).getCategory();
        String filePath = dirPath + "/PhotoViewer/" + folder + "/"
                + mPhotos.get(nextPosition - 1).getFileName();
        File imageFile = new File(filePath);
        Bitmap bitmap = BitmapFactory.decodeFile(imageFile
                .getAbsolutePath());
        WallpaperManager myWallpaperManager = WallpaperManager
                .getInstance(getApplicationContext());
        try {
            myWallpaperManager.setBitmap(bitmap);
            Toast.makeText(PhotoActivity.this, "Wallpaper set",
                    Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(PhotoActivity.this, "Error setting wallpaper",
                    Toast.LENGTH_SHORT).show();
        }

推荐答案

要在android中设置墙纸,请使用以下代码:通过使用WallpaperManager类

To set wallpaper in android use below code: By using WallpaperManager Class

Button buttonSetWallpaper = (Button)findViewById(R.id.set);
ImageView imagePreview = (ImageView)findViewById(R.id.preview);
imagePreview.setImageResource(R.drawable.five);

buttonSetWallpaper.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        WallpaperManager myWallpaperManager 
        = WallpaperManager.getInstance(getApplicationContext());
        try {
            myWallpaperManager.setResource(R.drawable.five);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
});

需要在清单中设置权限:

Need to set permission in Manifest:

<uses-permission android:name="android.permission.SET_WALLPAPER"/>

这篇关于如何使用代码在Android中设置墙纸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆