如何以编程方式将图像设置为墙纸?

use*_*635 6 java android wallpaper

我一直在开发需要将图像设置为壁纸的应用程序.

码:

WallpaperManager m=WallpaperManager.getInstance(this);

String s=Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg";
File f=new File(s);
Log.e("exist", String.valueOf(f.exists()));
try {
        InputStream is=new BufferedInputStream(new FileInputStream(s));
        m.setBitmap(BitmapFactory.decodeFile(s));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("File", e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.e("IO", e.getMessage());
    }
Run Code Online (Sandbox Code Playgroud)

我还添加了以下权限:

<uses-permission android:name="android.permission.SET_WALLPAPER" />
Run Code Online (Sandbox Code Playgroud)

但它不起作用; 该文件存在于SD卡上.我哪里弄错了?

小智 1

File f = new File(Environment.getExternalStorageDirectory(), "1.jpg");
String path = f.getAbsolutePath();
File f1 = new File(path);

if(f1.exists()) {
    Bitmap bmp = BitmapFactory.decodeFile(path);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
    WallpaperManager m=WallpaperManager.getInstance(this);

    try {
        m.setBitmap(bmp);
    } catch (IOException e) {
        e.printStackTrace();
    }
} 
Run Code Online (Sandbox Code Playgroud)

打开 Androidmanifest.xml 文件并添加权限,例如..

<uses-permission android:name="android.permission.SET_WALLPAPER" />
Run Code Online (Sandbox Code Playgroud)

试试这个,让我知道会发生什么..