Establecer fondo de pantalla desde un elemento de diseño

In my app, i need to get current wallpaper of the device:

Wallpaper = WallpaperManager.getInstance(getApplicationContext()).peekDrawable();

no, the problem is that this action will cause the UI to lag a bit while it's getting the background, furthermore, i need to set it as my app's background, i've tried this:

//Drawable Wallpaper defined already...

  new Thread(new Runnable() {
    public void run() {
      Wallpaper = WallpaperManager.getInstance(getApplicationContext()).peekDrawable();
    }
  }).start();
     if (Wallpaper == null)
       {                       
         //Resources res = getResources();
         //Drawable drawable1 = res.getDrawable(R.drawable.bg1);
         //getWindow().setBackgroundDrawable(drawable1);
     }
      else
        {
          Wallpaper.setAlpha(50);
          getWindow().setBackgroundDrawable(Wallpaper);
 }
      //........

but it's not working, any ideas? if possible, please give the code, i'm still kinda new to android.. also, is there a better way to do this?

preguntado el 02 de febrero de 12 a las 10:02

1 Respuestas

Try the following and see if it helps. I've commented the code for you to expand on (if needed).

private class SetWallpaperTask extends AsyncTask<Void, Void, Void> {

  Drawable wallpaperDrawable;

  @Override
  protected void onPreExecute() {
    // Runs on the UI thread
    // Do any pre-executing tasks here, for example display a progress bar
    Log.d(TAG, "About to set wallpaper...");
  }

  @Override
  protected Void doInBackground(Void... params) {
    // Runs on the background thread
    WallpaperManager wallpaperManager = WallpaperManager.getInstance
      (getApplicationContext());
    wallpaperDrawable = wallpaperManager.getDrawable();
  }

  @Override
  protected void onPostExecute(Void res) {
    // Runs on the UI thread
    // Here you can perform any post-execute tasks, for example remove the
    // progress bar (if you set one).
    if (wallpaperDrawable != null) {
      wallpaperDrawable.setAlpha(50);
      getWindow().setBackgroundDrawable(wallpaperDrawable);
      Log.d(TAG, "New wallpaper set");
    } else {
      Log.d(TAG, "Wallpaper was null");
    }
  }

}

And to execute this (background) task:

SetWallpaperTask t = new SetWallpaperTask();
t.execute();

If you're still stuck, I recommend you go through the SetWallpaperActivity.java example and try to replicate that.

Respondido 03 Feb 12, 16:02

it throws "Called from wrong thread" Exception, so i've moved the getwindows() part to onPostExecute and everything worked! thanks for the answer! - tom91136

@Tom91136 I figured it would throw something like that when trying to do UI stuff in the background thread :) I've updated my answer - thanks! - Marvin Pinto

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.