Link to a previous blog post
This blog post then describes the acquisition of local images.
Here's the code for the asynchronous thread class Loadloacalphotocursortask that gets the local picture:
/*** The asynchronous thread class that gets the local picture * / Public classLoadloacalphotocursortask extends Asynctask<object, Object, object> {PrivateContext Mcontext;PrivateFinal Contentresolver Mcontentresolver;PrivateBoolean mexittasksearly =false;//exit the task thread's flag bit PrivateOnloadphotocursor Onloadphotocursor;//Define callback interface to get parsed data PrivateArraylist<uri> Uriarray =NewArraylist<uri> ();//Store picture URI PrivateArraylist<long> Origidarray =NewArraylist<long> ();//Store image ID Public Loadloacalphotocursortask(Context Mcontext) { This. Mcontext = Mcontext; Mcontentresolver = Mcontext.getcontentresolver (); } @OverrideprotectedObjectDoinbackground(Object ...params{string[] projection = {mediastore.images.media._id}; Uri Ext_uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; Stringwhere= MediaStore.Images.Media.SIZE +">=?";/** * This query operation completes the image size larger than 100K image ID query. * You may wonder why you can't find the image data? * This is to save memory. Through the ID of the image can be queried to get the specified picture * If the picture data is queried here, the picture in the phone a large number of cases * memory consumption is serious. So, when to query the picture? It should be a query that completes a picture of the specified ID in adapter *, and does not load all the picture data at once * /Cursor C = MediaStore.Images.Media.query (Mcontentresolver, Ext_uri, Projecti Onwhere,Newstring[]{1* -*1024x768+""}, Mediastore.images.media.date_added+"desc");intColumnIndex = C.getcolumnindexorthrow (mediastore.images.media._id);inti =0; while(C.movetonext () && i < C.getcount () &&!mexittasksearly) {//move to the specified location, traverse the database LongOrigid = C.getlong (columnindex); Uriarray.add (Uri.withappendedpath (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Origid +"") ); Origidarray.add (Origid); C.movetoposition (i); i++; } c.close ();//Close Database if(mexittasksearly) {Uriarray =NewArraylist<uri> (); Origidarray =NewArraylist<long> (); }return NULL; } @Overrideprotected void OnPostExecute(Object o) {if(Onloadphotocursor! =NULL&&!mexittasksearly) {/** * After the query is complete, set the data in the callback interface and pass the data to the activity */Onloadphotocursor.onloadphotosursorresult (Uriarray, Origidarray); }} @Overrideprotected void oncancelled() {super.oncancelled ();//to change body of overridden methods use File | Settings | File Templates.Mexittasksearly =true; } Public void setexittasksearly(Boolean exittasksearly) { This. mexittasksearly = exittasksearly; } Public void Setonloadphotocursor(Onloadphotocursor onloadphotocursor) { This. onloadphotocursor = Onloadphotocursor; } Public InterfaceOnloadphotocursor { Public void Onloadphotosursorresult(arraylist<uri> Uriarray, arraylist<long> Origidarray); }}
Here's the code for the class Imageworker that loads the picture:
/** * Phone local image asynchronous Load processing class * Picture loading performance has a large impact, using weak references and soft references * cache pictures, speed up response speed, improve performance. */Public class imageworker { //This value is set to the time interval of animation effect of loading picture, achieve the effect of fade fade PrivateStaticFinalint fade_in_time = $;PrivateBoolean mexittasksearly =false;//Determine if the image loading task exits prematurely PrivateBoolean mpausework =false;//Load picture thread is pending Private FinalObject Mpauseworklock =NewObject ();//Lock object, this lock object is to determine whether to load the picture protected FinalResources mresources;Private FinalContentresolver Mcontentresolver;//Content resolver Private FinalBitmapfactory.options moptions;Private FinalHashmap<long, softreference<bitmapdrawable>> Bitmapcache =NewHashmap<long, softreference<bitmapdrawable>> ();//For caching pictures, each cached picture corresponds to a long ID value, softreference a soft reference to the image that should be PrivateBitmap Mloadbitmap;default background image in//gridview //BuilderPublic Imageworker (Context context) { This. mresources = Context.getresources (); This. Mcontentresolver = Context.getcontentresolver (); Moptions =NewBitmapfactory.options (); Moptions.insamplesize =3;//Zoom the image to the original 1/9. In general applications, loading pictures will be scaled to prevent memory overflow problems. This section is about bitmap, please refer to my blog (http://blog.csdn.net/u010156024/article/details/44103557)}/** * Load picture * @param origid Each local image corresponds to an ID value * @param imageView */public void LoadImage (long origid, ImageView ImageView) {bitmapdrawable bitmapdrawable =NULL;//load the picture from the cache first, if there is one in the cache, load the picture. //If not in the cache, first determine whether the current task is paused or not, and use the Loadbitmaptask async task line loads to load the picture if(Bitmapcache.containskey (Origid)) {bitmapdrawable = Bitmapcache.get (Origid). get (); }if(Bitmapdrawable! =NULL) {imageview.setimagedrawable (bitmapdrawable); }Else if(Cancelpotentialwork (Origid, ImageView)) {FinalLoadbitmaptask Loadbitmaptask =NewLoadbitmaptask (ImageView);FinalAsyncdrawable asyncdrawable =NewAsyncdrawable (Mresources, Mloadbitmap, Loadbitmaptask); Imageview.setimagedrawable (asyncdrawable);//serial_executor start thread to ensure that thread order executes sequentiallyLoadbitmaptask.executeonexecutor (Asynctask.serial_executor, Origid); } }/*** This class provides this method to set the default picture for each item in the GridView * /public void Setloadbitmap (Bitmap mloadbitmap) { This. Mloadbitmap = Mloadbitmap; }/** * Set image animation loading image fade fade effect * * @param imageView * @param drawable * * Privatevoid Setimagedrawable (ImageView ImageView, drawable drawable) {FinalTransitiondrawable td =NewTransitiondrawable (Newdrawable[]{NewColordrawable (Android. r.color.transparent), drawable}); Imageview.setimagedrawable (TD); Td.starttransition (Fade_in_time); }/** * Cancels a task that may be running and paused. * * @param origid * @param imageView * @return * * PrivateStatic Boolean cancelpotentialwork (Long Origid, ImageView ImageView) {FinalLoadbitmaptask loadbitmaptask = Getbitmapworkertask (ImageView);if(Loadbitmaptask! =NULL) {FinalLong bitmaporigid = Loadbitmaptask.origid;if(Bitmaporigid = = Origid) {Loadbitmaptask.cancel (true); }Else{//The same work was already in progress. return false; } }return true; }/** * Picture Asynchronous Load thread class-task thread */ Private class loadbitmaptask extends asynctask<Long, Void, bitmapdrawable> { PrivateLong Origid;PrivateWeakreference<imageview> imageviewreference;//pointing to ImageView's weak reference, the picture is cached in Hashmap<long, softreference<bitmapdrawable>> Bitmapcache. Public Loadbitmaptask (ImageView ImageView) {imageviewreference =NewWeakreference<imageview> (ImageView); }@Override protectedBitmapdrawable doinbackground (Long ... params) {Origid = params[0]; Bitmap Bitmap =NULL; Bitmapdrawable drawable =NULL;//Wait here if paused and the task are not cancelledSynchronized (Mpauseworklock) { while(Mpausework &&!iscancelled ()) {Try{mpauseworklock.wait (); }Catch(Interruptedexception e) { } } }if(Bitmapcache! =NULL&&!iscancelled () && getattachedimageview ()! =NULL&&!mexittasksearly) {//Here is based on the image ID value of the phone to query local images, get pictures of thumbnails, Micro_kind represents 96*96 size of the pictureBitmap = MediaStore.Images.Thumbnails.getThumbnail (Mcontentresolver, Origid , MediaStore.Images.Thumbnails.MICRO_KIND, moptions); }if(Bitmap! =NULL) {drawable =NewBitmapdrawable (mresources, bitmap); Bitmapcache.put (Origid,NewSoftreference<bitmapdrawable> (drawable)); }returndrawable; }@Override protectedvoid OnPostExecute (Bitmapdrawable drawable) {if(iscancelled () | | mexittasksearly) {drawable =NULL; }FinalImageView ImageView = Getattachedimageview ();if(Drawable! =NULL&& ImageView! =NULL) {setimagedrawable (ImageView, drawable); } }@Override protectedvoid oncancelled (Bitmapdrawable drawable) {Super. oncancelled (drawable); Synchronized (Mpauseworklock) {mpauseworklock.notifyall (); } }/** * Returns the ImageView associated with this task, * if the task within ImageView is the current task, * Returns the current ImageView, otherwise returns NULL. * @return * * PrivateImageView Getattachedimageview () {FinalImageView ImageView = Imageviewreference.get ();FinalLoadbitmaptask bitmapworkertask = Getbitmapworkertask (ImageView);if( This= = Bitmapworkertask) {returnImageView; }return NULL; } }/** * Storing asynchronous information Picture Resource class */ PrivateStatic class asyncdrawable extends bitmapdrawable { Private FinalWeakreference<loadbitmaptask> bitmapworkertaskreference;//Virtual referencePublic Asyncdrawable (Resources res, Bitmap Bitmap, Loadbitmaptask bitmapworkertask) {Super(res, bitmap); Bitmapworkertaskreference =NewWeakreference<loadbitmaptask> (Bitmapworkertask); } public Loadbitmaptask Getloadbitmaptask () {returnBitmapworkertaskreference.get (); } }/** * Returns the asynchronous thread that is stored within the picture resource, returns if it exists, does not exist, and returns NULL. * * @param imageView Current ImageView * @return * * * for the image of the asynchronous resource PrivateStatic Loadbitmaptask Getbitmapworkertask (ImageView ImageView) {if(ImageView! =NULL) {Finaldrawable drawable = imageview.getdrawable ();if(drawable instanceof Asyncdrawable) {FinalAsyncdrawable asyncdrawable = (asyncdrawable) drawable;returnAsyncdrawable.getloadbitmaptask (); } }return NULL; }/** * Sets whether the asynchronous task is paused, false for startup, and true for pause. * @param pausework * *public void Setpausework (Boolean pausework) {synchronized (mpauseworklock) {mpausework = Pausework;if(!mpausework) {Mpauseworklock.notifyall (); } } }/** * Exit thread * @param exittasksearly */public void Setexittasksearly (Boolean exittasksearly) {mexittasksearly = exittasksearly; Setpausework (false);//This setting is false, which makes the exit task graceful. This setting is true also possible, and there is no problem, can achieve the same effect. However, you can compare the differences that are set to true or false. }}
This is all about getting the entire contents of your local image on your Android phone. This project code is open to GitHub, and it's worth studying in depth.
Summarize:
The whole project uses contentresolver, soft references, weak references, caches, asynchronous threads, memory-saving tricks-scrolling without loading, locking mechanisms, image scaling, threading, animations, and more.
SOURCE download
Android get local pictures (ii)