Android Development Template Code (a)--Simple open Gallery Select photos

Source: Internet
Author: User

First, paste the sample code first.

//Check Permissions     Public voidcheckpermission () {if(Contextcompat.checkselfpermission ( This, Manifest.permission.WRITE_EXTERNAL_STORAGE)! =packagemanager.permission_granted) {Activitycompat.requestpermissions ( This,NewString[]{manifest.permission.write_external_storage}, 1); //found no permissions, call the Requestpermissions method to apply permissions to the user, requestpermissions receive three parameters, the first is the context, the second is a string array, we put the permission to apply//name in the array, and the third is the request code, as long as it's a unique value.}Else{openalbum ();//Open album with permission        }    }     Public voidOpenalbum () {//Open the album through intent, using the Startactivityforresult method to start Actvity, will return to the Onactivityresult method, so we have to replicate the Onactivityresult methodIntent Intent =NewIntent ("Android.intent.action.GET_CONTENT"); Intent.settype ("Image/*");    Startactivityforresult (Intent, Choose_photo); }    //Pop-up window requesting permission from user@Override Public voidOnrequestpermissionsresult (intRequestcode, @NonNull string[] permissions, @NonNullint[] grantresults) {        Super. Onrequestpermissionsresult (Requestcode, permissions, grantresults);//Popup Authorization window, this statement can also be deleted, without affecting//Obtain the user's authorization result, save in grantresults, judge the result in Grantresult to decide the next action        Switch(requestcode) { Case1:                if(Grantresults.length > 0 && grantresults[0] = =packagemanager.permission_granted)                {openalbum (); } Else{Toast.maketext ( This, "Authorization failed, unable to operate", Toast.length_short). Show (); }                 Break; default:                 Break; }} @Overrideprotected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {        Super. Onactivityresult (Requestcode, ResultCode, data); Switch(requestcode) { CaseChoose_photo:if(ResultCode = =RESULT_OK) {                    if(Build.VERSION.SDK_INT >= 19) {Handleimageonkitkat (data);//above 4.4 Version Use this method to process pictures}Else{handleimagebeforekitkat (data);//below 4.4 Version Use this method to process pictures                    }                }                 Break; default:                 Break; }} @TargetApi (19)    Private voidHandleimageonkitkat (Intent data) {String ImagePath=NULL; Uri URI=Data.getdata (); if(Documentscontract.isdocumenturi ( This, Uri)) {            //if it is a URI of document type, it is handled by the document IDString docId =Documentscontract.getdocumentid (URI); if("Com.android.providers.media.documents". Equals (Uri.getauthority ())) {String ID= Docid.split (":") [1];//resolves the id of a number formatString selection = mediastore.images.media._id + "=" +ID; ImagePath=Getimagepath (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } Else if("Com.android,providers.downloads.documents". Equals (Uri.getauthority ())) {Uri Contenturi= Contenturis.withappendedid (Uri.parse ("Content://downloads/public_downloads"), long.valueof (docId)); ImagePath= Getimagepath (Contenturi,NULL); }        } Else if("Content". Equalsignorecase (Uri.getscheme ())) {ImagePath= Getimagepath (URI,NULL);    } displayimage (ImagePath); }    Private voidHandleimagebeforekitkat (Intent data) {URI URI=Data.getdata (); String ImagePath= Getimagepath (URI,NULL);    DisplayImage (ImagePath); }    //get the picture path     Publicstring Getimagepath (Uri uri, string selection) {string path=NULL; Cursor Cursor= Getcontentresolver (). Query (URI,NULL, Selection,NULL,NULL);//content providers        if(Cursor! =NULL) {            if(Cursor.movetofirst ()) {path= Cursor.getstring (Cursor.getcolumnindex (MediaStore.Images.Media.DATA));//Get Path}} cursor.close (); returnpath; }    //Show Pictures    Private voiddisplayimage (String imagePath) {if(ImagePath! =NULL) {Bitmap bitimage= Bitmapfactory.decodefile (ImagePath);//Formatting PicturesMimage.setimagebitmap (bitimage);//set up a picture for ImageView        } Else{toast.maketext (mainactivity). This, "Get Picture Failed", Toast.length_short). Show (); }    }
Instruction for use: First, add memory card permissions in the Androidmanifest file
<android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/> 
Second, through the Findviewbyid to find the button or ImageButton, and bound to listen to the event three, copy the above sample code placed under the OnClick event, at the same time, add a global static variable

Call the Checkpermission method on a button or a ImageButton click event

Five, through the Findviewbyid to find ImageView, modify the Display method call set the object name of the image in the actual project ImageView object name, details can see the Code Red part, will mimage modify the simple logic introduction:

Draw a flowchart, the logic is still relatively clear, here do not do too much explanation

PS: In fact, you can also add the operation of the last side of the crop picture, after the setting of the picture, I went to the degree of Niang search data, see still very confused force, and so on, and then do a thorough study to supplement

Demo download

Android Development Template Code (a)--Simple open Gallery Select photos

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.