从drawable设置背景壁纸

时间:2012-02-02 10:55:22

标签: java android android-asynctask drawable wallpaper

在我的应用中,我需要获取设备的当前壁纸:

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

不,问题是这个动作会导致UI在获得背景时滞后一点,而且,我需要将其设置为我的应用程序的背景,我已经试过这个:

//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);
 }
      //........

但它没有用,有什么想法吗? 如果可能的话,请给出代码,我仍然是一个新的Android .. 还有,有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

尝试以下操作,看看是否有帮助。我已经评论了代码供您扩展(如果需要)。

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

}

执行此(后台)任务:

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

如果您仍然卡住,我建议您浏览SetWallpaperActivity.java示例并尝试复制该内容。