case MENU_WALLPAPER_SETTINGS: startWallpaper();//點擊壁紙設定菜單,會調用startWallpaper() private void startWallpaper() { closeAllApps(true); final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); Intent chooser = Intent.createChooser(pickWallpaper, getText(R.string.chooser_wallpaper)); startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); } //createChooser 會彈出一個對話方塊,把能處理Intent.ACTION_SET_WALLPAPER //的activity都列出來供使用者選擇
選擇“壁紙”後會啟動Activity:WallpaperChooser
介面由三個View組成:ImageView 、Gallery、Button,
點擊Button後,設定壁紙:
private void selectWallpaper(int position) { if (mIsWallpaperSet) { return; } mIsWallpaperSet = true; try { WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE); wpm.setResource(mImages.get(position)); setResult(RESULT_OK); finish(); } catch (IOException e) { Log.e(TAG, "Failed to set wallpaper: " + e); } }
Gallery的item被選擇後,ImageView會把相對應的大的圖片顯示出來,
此處通過非同步處理類asynctask來完成的:
public void onItemSelected(AdapterView parent, View v, int position, long id) { if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) { mLoader.cancel(); } mLoader = (WallpaperLoader) new WallpaperLoader().execute(position); }
其中execute的參數position就是AsyncTask的doInBackground後面的參數,
doInBackground return的值,會作為onPostExecute的參數
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> { BitmapFactory.Options mOptions; WallpaperLoader() { mOptions = new BitmapFactory.Options(); mOptions.inDither = false; mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; } protected Bitmap doInBackground(Integer... params)//此處params為position { if (isCancelled()) return null; try { return BitmapFactory.decodeResource(getResources(), mImages.get(params[0]), mOptions); } catch (OutOfMemoryError e) { Log.w(TAG, "Home no memory load current wallpaper", e); return null; } } @Override protected void onPostExecute(Bitmap b) //此處的b為doInBackGround return的值 { if (b == null) return; if (!isCancelled() && !mOptions.mCancel) { // Help the GC if (mBitmap != null) { mBitmap.recycle(); } final ImageView view = mImageView; view.setImageBitmap(b); mBitmap = b; final Drawable drawable = view.getDrawable(); drawable.setFilterBitmap(true); //用來對Bitmap進行濾波處理,有消除鋸齒的效果 drawable.setDither(true);//防震 view.postInvalidate(); mLoader = null; } else { b.recycle(); } } void cancel() { mOptions.requestCancelDecode(); super.cancel(true); } }}