1 package js.kbars; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.graphics.Bitmap; 6 import android.graphics.Bitmap.CompressFormat; 7 import android.graphics.BitmapFactory; 8 import android.graphics.drawable.BitmapDrawable; 9 import android.view.Menu; 10 import android.view.MenuItem; 11 import android.view.MenuItem.OnMenuItemClickListener; 12 import android.view.View; 13 import java.io.File; 14 import java.io.FileNotFoundException; 15 import java.io.FileOutputStream; 16 import java.io.IOException; 17 18 public final class CameraBackgroundMenuItem implements OnMenuItemClickListener { 19 public static final int REQUEST_CODE = 123; 20 private final Activity mActivity; 21 private final View mTarget; 22 23 public CameraBackgroundMenuItem(Menu menu, Activity activity, View target) { 24 this.mActivity = activity; 25 this.mTarget = target; 26 menu.add("Camera image background...").setOnMenuItemClickListener(this); 27 loadBitmap(); 28 } 29 30 public boolean onMenuItemClick(MenuItem item) { 31 chooseBackground(); 32 return true; 33 } 34 35 public void onActivityResult(int resultCode, Intent data) { 36 if (resultCode == -1) { 37 Bitmap bitmap = (Bitmap) data.getParcelableExtra("data"); 38 if (bitmap != null) { 39 setTargetBackground(bitmap); 40 saveBitmap(bitmap); 41 } 42 } 43 } 44 45 private void chooseBackground() { 46 this.mActivity.startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), REQUEST_CODE); 47 } 48 49 private File bitmapFile() { 50 return new File(this.mActivity.getCacheDir(), "background.png"); 51 } 52 53 private void saveBitmap(Bitmap bitmap) { 54 FileNotFoundException e; 55 Throwable th; 56 File f = bitmapFile(); 57 if (f.exists()) { 58 f.delete(); 59 } 60 if (bitmap != null) { 61 FileOutputStream out = null; 62 try { 63 FileOutputStream out2 = new FileOutputStream(f); 64 bitmap.compress(CompressFormat.PNG, 100, out2); 65 out2.close(); 66 } catch (FileNotFoundException e1) { 67 e1.printStackTrace(); 68 } catch (IOException e1) { 69 e1.printStackTrace(); 70 } 71 } 72 } 73 74 private void loadBitmap() { 75 Bitmap bitmap = loadBitmapFromCache(); 76 if (bitmap == null) { 77 bitmap = loadBitmapFromAssets(); 78 } 79 setTargetBackground(bitmap); 80 } 81 82 private Bitmap loadBitmapFromCache() { 83 File f = bitmapFile(); 84 return f.exists() ? BitmapFactory.decodeFile(f.getAbsolutePath()) : null; 85 } 86 87 private Bitmap loadBitmapFromAssets() { 88 try { 89 return BitmapFactory.decodeStream(this.mActivity.getAssets().open("background.png")); 90 } catch (IOException e) { 91 throw new RuntimeException(e); 92 } 93 } 94 95 private void setTargetBackground(Bitmap bitmap) { 96 if (bitmap == null) { 97 this.mTarget.setBackground(null); 98 } else { 99 this.mTarget.setBackground(new BitmapDrawable(this.mActivity.getResources(), bitmap)); 100 } 101 } 102 } 103