2012-04-15 85 views
6

Tôi đã phát triển ứng dụng cần đặt hình ảnh làm hình nền.Cách đặt hình ảnh làm hình nền theo chương trình?

Code:

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

Ngoài ra tôi đã thêm các quyền sau:

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

Nhưng nó không hoạt động; tệp tồn tại trên sdcard. Tôi đã phạm sai lầm ở đâu?

+1

có trường hợp ngoại lệ không? –

Trả lời

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

mở AndroidManifest.xml tập tin và thêm phép như ..

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

Hãy thử điều này và cho tôi biết những gì xảy ra ..

5

Có thể, bạn chạy ra khỏi bộ nhớ nếu hình ảnh của bạn là to. Bạn có thể chắc chắn bằng cách đọc nhật ký Logcat. Nếu trường hợp này xảy ra, hãy thử điều chỉnh hình ảnh của bạn thành kích thước thiết bị bằng một phần như sau:

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); 
    } 
Các vấn đề liên quan