2012-04-15 16 views
6

He estado desarrollando la aplicación que necesita establecer una imagen como fondo de pantalla.¿Cómo establecer la imagen como fondo de pantalla mediante programación?

Código:

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

También he añadido el siguiente permiso:

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

Pero no hace las obras; el archivo existe en sdcard. ¿Dónde he cometido un error?

+1

¿Hay una excepción lanzada? –

Respuesta

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

abierto AndroidManifest.xml archivo y añadir el permiso como ..

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

Prueba esto y quiero saber lo que suceda ..

5

Posiblemente, se ejecuta fuera de la memoria si la imagen es grande. Puede asegurarse de ello leyendo los registros de Logcat. Si este es el caso, intente ajustar su imagen al tamaño del dispositivo de la siguiente manera:

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