2012-04-15 126 views
6

我一直在開發需要設置圖像作爲壁紙的應用程序。如何以編程方式將圖像設置爲壁紙?

代碼:

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

而且我已經添加了以下權限:

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

但它不工作;該文件存在於SD卡上。我在哪裏犯了一個錯誤?

+1

是否有拋出異常? – 2012-04-15 07:24:34

回答

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

打開AndroidManifest.xml文件,並添加權限如..

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

試試這個,讓我知道發生什麼事..

5

可能的話,你耗盡內存,如果你的形象大。你可以通過閱讀Logcat日誌來確定它。如果是這種情況,嘗試調整您的圖片到設備的大小有點像這樣:

DisplayMetrics displayMetrics = new DisplayMetrics(); 
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); 
    int height = displayMetrics.heightPixels; 
    int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, width, height); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options); 

    WallpaperManager wm = WallpaperManager.getInstance(this); 
    try { 
     wm.setBitmap(decodedSampleBitmap); 
    } catch (IOException e) { 
     Log.e(TAG, "Cannot set image as wallpaper", e); 
    } 
相關問題