handled this by saving the image to the ContentProvider
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI and then
saving the created URI to the database along with my item. An example
of how to do this can be found here:
- /*
- *Copyright(C)2008GoogleInc.
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagecom.google.android.photostream;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.content.Intent;
- importandroid.content.ActivityNotFoundException;
- importandroid.os.Bundle;
- importandroid.widget.TextView;
- importandroid.widget.ImageView;
- importandroid.widget.ViewAnimator;
- importandroid.widget.LinearLayout;
- importandroid.widget.Toast;
- importandroid.graphics.Bitmap;
- importandroid.graphics.BitmapFactory;
- importandroid.graphics.drawable.Drawable;
- importandroid.graphics.drawable.BitmapDrawable;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.view.ViewTreeObserver;
- importandroid.view.Menu;
- importandroid.view.MenuItem;
- importandroid.view.animation.AnimationUtils;
- importandroid.net.Uri;
- importjava.io.File;
- importjava.io.IOException;
- importjava.io.OutputStream;
- importjava.io.InputStream;
- importjava.io.FileNotFoundException;
- /**
- *Activitythatdisplaysaphotoalongwithitstitleandthedateatwhichitwastaken.
- *Thisactivityalsoletstheusersetthephotoasthewallpaper.
- */
- publicclassViewPhotoActivityextendsActivityimplementsView.OnClickListener,
- ViewTreeObserver.OnGlobalLayoutListener{
- staticfinalStringACTION="com.google.android.photostream.FLICKR_PHOTO";
- privatestaticfinalStringRADAR_ACTION="com.google.android.radar.SHOW_RADAR";
- privatestaticfinalStringRADAR_EXTRA_LATITUDE="latitude";
- privatestaticfinalStringRADAR_EXTRA_LONGITUDE="longitude";
- privatestaticfinalStringEXTRA_PHOTO="com.google.android.photostream.photo";
- privatestaticfinalStringWALLPAPER_FILE_NAME="wallpaper";
- privatestaticfinalintREQUEST_CROP_IMAGE=42;
- privateFlickr.PhotomPhoto;
- privateViewAnimatormSwitcher;
- privateImageViewmPhotoView;
- privateViewGroupmContainer;
- privateUserTask<?,?,?>mTask;
- privateTextViewmPhotoTitle;
- privateTextViewmPhotoDate;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- mPhoto=getPhoto();
- setContentView(R.layout.screen_photo);
- setupViews();
- }
- /**
- *StartstheViewPhotoActivityforthespecifiedphoto.
- *
- *@paramcontextTheapplication'senvironment.
- *@paramphotoThephototodisplayandoptionallysetasawallpaper.
- */
- staticvoidshow(Contextcontext,Flickr.Photophoto){
- finalIntentintent=newIntent(context,ViewPhotoActivity.class);
- intent.putExtra(EXTRA_PHOTO,photo);
- context.startActivity(intent);
- }
- @Override
- protectedvoidonDestroy(){
- super.onDestroy();
- if(mTask!=null&&mTask.getStatus()!=UserTask.Status.RUNNING){
- mTask.cancel(true);
- }
- }
- privatevoidsetupViews(){
- mContainer=(ViewGroup)findViewById(R.id.container_photo);
- mSwitcher=(ViewAnimator)findViewById(R.id.switcher_menu);
- mPhotoView=(ImageView)findViewById(R.id.image_photo);
- mPhotoTitle=(TextView)findViewById(R.id.caption_title);
- mPhotoDate=(TextView)findViewById(R.id.caption_date);
- findViewById(R.id.menu_back).setOnClickListener(this);
- findViewById(R.id.menu_set).setOnClickListener(this);
- mPhotoTitle.setText(mPhoto.getTitle());
- mPhotoDate.setText(mPhoto.getDate());
- mContainer.setVisibility(View.INVISIBLE);
- //Setsupaviewtreeobserver.Thephotowillbescaledusingthesize
- //ofoneofourviewssowemustwaitforthefirstlayoutpasstobe
- //donetomakesurewehavethecorrectsize.
- mContainer.getViewTreeObserver().addOnGlobalLayoutListener(this);
- }
- /**
- *Loadsthephotoafterthefirstlayout.Thephotoisscaledusingthe
- *dimensionoftheImageViewthatwillultimatelycontainthephoto's
- *bitmap.WemakesurethattheImageViewislaidoutatleastonceto
- *getitscorrectsize.
- */
- publicvoidonGlobalLayout(){
- mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
- loadPhoto(mPhotoView.getMeasuredWidth(),mPhotoView.getMeasuredHeight());
- }
- /**
- *Loadsthephotoeitherfromthelastknowninstanceorfromthenetwork.
- *Loadingitfromthelastknowninstanceallowsforfastdisplayrotation
- *withouthavingtodownloadthephotofromthenetworkagain.
- *
- *@paramwidthThedesiredmaximumwidthofthephoto.
- *@paramheightThedesiredmaximumheightofthephoto.
- */
- privatevoidloadPhoto(intwidth,intheight){
- finalObjectdata=getLastNonConfigurationInstance();
- if(data==null){
- mTask=newLoadPhotoTask().execute(mPhoto,width,height);
- }else{
- mPhotoView.setImageBitmap((Bitmap)data);
- mSwitcher.showNext();
- }
- }
- /**
- *Loadsthe{@linkcom.google.android.photostream.Flickr.Photo}todisplay
- *fromtheintentusedtostarttheactivity.
- *
- *@returnThephototodisplay,ornullifthephotocannotbefound.
- */
- publicFlickr.PhotogetPhoto(){
- finalIntentintent=getIntent();
- finalBundleextras=intent.getExtras();
- Flickr.Photophoto=null;
- if(extras!=null){
- photo=extras.getParcelable(EXTRA_PHOTO);
- }
- returnphoto;
- }
- @Override
- publicbooleanonCreateOptionsMenu(Menumenu){
- getMenuInflater().inflate(R.menu.view_photo,menu);
- returnsuper.onCreateOptionsMenu(menu);
- }
- @Override
- publicbooleanonMenuItemSelected(intfeatureId,MenuItemitem){
- switch(item.getItemId()){
- caseR.id.menu_item_radar:
- onShowRadar();
- break;
- }
- returnsuper.onMenuItemSelected(featureId,item);
- }
- privatevoidonShowRadar(){
- newShowRadarTask().execute(mPhoto);
- }
- publicvoidonClick(Viewv){
- switch(v.getId()){
- caseR.id.menu_back:
- onBack();
- break;
- caseR.id.menu_set:
- onSet();
- break;
- }
- }
- privatevoidonSet(){
- mTask=newCropWallpaperTask().execute(mPhoto);
- }
- privatevoidonBack(){
- finish();
- }
- /**
- *Ifwesuccessfullyloadedaphoto,sendittoourfutureselftoallow
- *forfastdisplayrotation.Bydoingso,weavoidreloadingthephoto
- *fromthenetworkwhentheactivityistakendownandrecreatedupon
- *displayrotation.
- *
- *@returnTheBitmapdisplayedintheImageView,ornullifthephoto
- *wasn'tloaded.
- */
- @Override
- publicObjectonRetainNonConfigurationInstance(){
- finalDrawabled=mPhotoView.getDrawable();
- returnd!=null?((BitmapDrawable)d).getBitmap():null;
- }
- @Override
- protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
- //Spawnsanewtasktosetthewallpaperinabackgroundthreadwhen/if
- //wereceiveasuccessfulresultfromtheimagecropper.
- if(requestCode==REQUEST_CROP_IMAGE){
- if(resultCode==RESULT_OK){
- mTask=newSetWallpaperTask().execute();
- }else{
- cleanupWallpaper();
- showWallpaperError();
- }
- }
- }
- privatevoidshowWallpaperError(){
- Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_save_file,
- Toast.LENGTH_SHORT).show();
- }
- privatevoidshowWallpaperSuccess(){
- Toast.makeText(ViewPhotoActivity.this,R.string.success_wallpaper_set,
- Toast.LENGTH_SHORT).show();
- }
- privatevoidcleanupWallpaper(){
- deleteFile(WALLPAPER_FILE_NAME);
- mSwitcher.showNext();
- }
- /**
- *BackgroundtasktoloadthephotofromFlickr.Thetaskloadsthebitmap,
- *thenscaleittotheappropriatedimension.Thetaskendsbyreadjusting
- *theactivity'slayoutsothateverythingalignscorrectly.
- */
- privateclassLoadPhotoTaskextendsUserTask<Object,Void,Bitmap>{
- publicBitmapdoInBackground(Object...params){
- Bitmapbitmap=((Flickr.Photo)params[0]).loadPhotoBitmap(Flickr.PhotoSize.MEDIUM);
- if(bitmap==null){
- bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.not_found);
- }
- finalintwidth=(Integer)params[1];
- finalintheight=(Integer)params[2];
- finalBitmapframed=ImageUtilities.scaleAndFrame(bitmap,width,height);
- bitmap.recycle();
- returnframed;
- }
- @Override
- publicvoidonPostExecute(Bitmapresult){
- mPhotoView.setImageBitmap(result);
- //Findbyhowmanypixelsthetitleanddatemustbeshiftedonthe
- //horizontalaxistobeleftalignedwiththephoto
- finalintoffsetX=(mPhotoView.getMeasuredWidth()-result.getWidth())/2;
- //ForcestheImageViewtohavethesamesizeasitsembeddedbitmap
- //Thiswillremovetheemptyspacebetweenthetitle/datepairand
- //thephotoitself
- LinearLayout.LayoutParamsparams;
- params=(LinearLayout.LayoutParams)mPhotoView.getLayoutParams();
- params.height=result.getHeight();
- params.weight=0.0f;
- mPhotoView.setLayoutParams(params);
- params=(LinearLayout.LayoutParams)mPhotoTitle.getLayoutParams();
- params.leftMargin=offsetX;
- mPhotoTitle.setLayoutParams(params);
- params=(LinearLayout.LayoutParams)mPhotoDate.getLayoutParams();
- params.leftMargin=offsetX;
- mPhotoDate.setLayoutParams(params);
- mSwitcher.showNext();
- mContainer.startAnimation(AnimationUtils.loadAnimation(ViewPhotoActivity.this,
- R.anim.fade_in));
- mContainer.setVisibility(View.VISIBLE);
- mTask=null;
- }
- }
- /**
- *Backgroundtasktocropalargeversionoftheimage.Thecroppedresultwill
- *besetasawallpaper.Thetaskssartsbyshowingtheprogressbar,then
- *downloadsthelargeversionofhthephotointoatemporaryfileandendsby
- *sendinganintenttotheCameraapplicationtocroptheimage.
- */
- privateclassCropWallpaperTaskextendsUserTask<Flickr.Photo,Void,Boolean>{
- privateFilemFile;
- @Override
- publicvoidonPreExecute(){
- mFile=getFileStreamPath(WALLPAPER_FILE_NAME);
- mSwitcher.showNext();
- }
- publicBooleandoInBackground(Flickr.Photo...params){
- booleansuccess=false;
- OutputStreamout=null;
- try{
- out=openFileOutput(mFile.getName(),MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE);
- Flickr.get().downloadPhoto(params[0],Flickr.PhotoSize.LARGE,out);
- success=true;
- }catch(FileNotFoundExceptione){
- android.util.Log.e(Flickr.LOG_TAG,"Couldnotdownloadphoto",e);
- success=false;
- }catch(IOExceptione){
- android.util.Log.e(Flickr.LOG_TAG,"Couldnotdownloadphoto",e);
- success=false;
- }finally{
- if(out!=null){
- try{
- out.close();
- }catch(IOExceptione){
- success=false;
- }
- }
- }
- returnsuccess;
- }
- @Override
- publicvoidonPostExecute(Booleanresult){
- if(!result){
- cleanupWallpaper();
- showWallpaperError();
- }else{
- finalintwidth=getWallpaperDesiredMinimumWidth();
- finalintheight=getWallpaperDesiredMinimumHeight();
- finalIntentintent=newIntent("com.android.camera.action.CROP");
- intent.setClassName("com.android.camera","com.android.camera.CropImage");
- intent.setData(Uri.fromFile(mFile));
- intent.putExtra("outputX",width);
- intent.putExtra("outputY",height);
- intent.putExtra("aspectX",width);
- intent.putExtra("aspectY",height);
- intent.putExtra("scale",true);
- intent.putExtra("noFaceDetection",true);
- intent.putExtra("output",Uri.parse("file:/"+mFile.getAbsolutePath()));
- startActivityForResult(intent,REQUEST_CROP_IMAGE);
- }
- mTask=null;
- }
- }
- /**
- *Backgroundtasktosetthecroppedimageasthewallpaper.Thetasksimply
- *openthetemporaryfileandsetsitasthenewwallpaper.Thetaskendsby
- *deletingthetemporaryfileanddisplayamessagetotheuser.
- */
- privateclassSetWallpaperTaskextendsUserTask<Void,Void,Boolean>{
- publicBooleandoInBackground(Void...params){
- booleansuccess=false;
- InputStreamin=null;
- try{
- in=openFileInput(WALLPAPER_FILE_NAME);
- setWallpaper(in);
- success=true;
- }catch(IOExceptione){
- success=false;
- }finally{
- if(in!=null){
- try{
- in.close();
- }catch(IOExceptione){
- success=false;
- }
- }
- }
- returnsuccess;
- }
- @Override
- publicvoidonPostExecute(Booleanresult){
- cleanupWallpaper();
- if(!result){
- showWallpaperError();
- }else{
- showWallpaperSuccess();
- }
- mTask=null;
- }
- }
- privateclassShowRadarTaskextendsUserTask<Flickr.Photo,Void,Flickr.Location>{
- publicFlickr.LocationdoInBackground(Flickr.Photo...params){
- returnFlickr.get().getLocation(params[0]);
- }
- @Override
- publicvoidonPostExecute(Flickr.Locationlocation){
- if(location!=null){
- finalIntentintent=newIntent(RADAR_ACTION);
- intent.putExtra(RADAR_EXTRA_LATITUDE,location.getLatitude());
- intent.putExtra(RADAR_EXTRA_LONGITUDE,location.getLongitude());
- try{
- startActivity(intent);
- }catch(ActivityNotFoundExceptione){
- Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_find_radar,
- Toast.LENGTH_SHORT).show();
- }
- }else{
- Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_find_location,
- Toast.LENGTH_SHORT).show();
- }
- }
- }
- }