Android development template code (1)-simply open the image library and select a photo,

Source: Internet
Author: User

Android development template code (1)-simply open the image library and select a photo,

First, paste the sample code

// Check the permission public void checkPermission () {if (ContextCompat. checkSelfPermission (this, Manifest. permission. WRITE_EXTERNAL_STORAGE )! = PackageManager. PERMISSION_GRANTED) {ActivityCompat. requestPermissions (this, new String [] {Manifest. permission. WRITE_EXTERNAL_STORAGE}, 1); // if no permission is found, the requestPermissions method is called to apply for permission from the user. requestPermissions receives three parameters. The first parameter is context, and the second parameter is a String array, we can put the applied permission // name in the array, and the third is the request code, as long as it is a unique value} else {openAlbum (); // open the album with the permission} public void openAlbum () {// open the album with intent and start actvity using startactivityForResult. onActivityResu So we have to re-write the onActivityResult method Intent intent = new Intent ("android. intent. action. GET_CONTENT "); intent. setType ("image/*"); startActivityForResult (intent, CHOOSE_PHOTO);} // In the displayed window, apply for permissions from the user @ Override public void onRequestPermissionsResult (int requestCode, @ NonNull String [] permissions, @ NonNull int [] grantResults) {super. onRequestPermissionsResult (requestCode, permissions, grantResults); // The authorization window is displayed. Statement can also be deleted, without affecting // obtain the user's authorization result, save it in grantResults, judge the result in grantResult to determine the next operation switch (requestCode) {case 1: 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 ;}@ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onAc TivityResult (requestCode, resultCode, data); switch (requestCode) {case CHOOSE_PHOTO: if (resultCode = RESULT_ OK) {if (Build. VERSION. SDK_INT> = 19) {handleImageOnkitKat (data); // use this method to process images later than version 4.4} else {handleImageBeforeKitKat (data ); // use this method to process images earlier than version 4.4} break; default: break; }}@ TargetApi (19) private void handleImageOnkitKat (Intent data) {String imagePath = null; uri uri = data. getData (); If (DocumentsContract. isDocumentUri (this, uri) {// if it is a document-type uri, the String docId = DocumentsContract is processed by the document id. getentid (uri); if ("com.android.providers.media.doc uments ". equals (uri. getAuthority () {String id = docId. split (":") [1]; // parse the digital format id String selection = MediaStore. images. media. _ ID + "=" + id; imagePath = getImagePath (MediaStore. images. media. EXTERNAL_CONTENT_URI, selection) ;} Else if ("com.android,providers.downloads.doc uments ". 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 void handleImageBe ForeKitKat (Intent data) {Uri uri = data. getData (); String imagePath = getImagePath (uri, null); displayImage (imagePath);} // obtain the image path public String getImagePath (Uri uri, String selection) {String path = null; Cursor cursor = getContentResolver (). query (uri, null, selection, null, null); // if (cursor! = Null) {if (cursor. moveToFirst () {path = cursor. getString (cursor. getColumnIndex (MediaStore. images. media. DATA); // obtain the path} cursor. close (); return path;} // display the image private void displayImage (String imagePath) {if (imagePath! = Null) {Bitmap bitImage = BitmapFactory. decodeFile (imagePath); // format the imageMImage. setImageBitmap (bitImage );// Set the image for imageView} else {Toast. makeText (MainActivity. this, "failed to get the image", Toast. LENGTH_SHORT). show ();}}
Instructions for use: 1. Add the storage card permission to the AndroidManiFest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2. Find the Button or imageButton through findviewbyid and bind the listener event. 3. Copy the sample code and place it under the onClick event. Add a Global static variable.

 

4. Call the checkPermission method in the button or imageButton Click Event

5. Find the ImageView through findviewbyid, modify the call in the display method to set the image object name to the imageView object name in the actual project. For details, refer to the Code highlighted, modify the mImage to provide a brief introduction to the logic:

After drawing a flowchart, the logic is clear and I will not describe it too much here.

 

PS: in fact, you can add a cropping image at the end of the page. Then, when setting up the image, I searched for the information on the top of the screen and looked at it very hard. I will make a supplement after thorough research.

Download Demo

 

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.