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