"Android" Memory card picture reader, gallery app

Source: Internet
Author: User
Tags exit in

Previous "Android" read all the pictures on the SDcard card and show that the reading process has a progress bar display (click the Open link) test on the real machine is very problematic, often encountered memory overflow, the situation of the card dead. Because of the memory on the real machine now, 2G has rarely seen, basically all 8G look like. This app is unfriendly because it puts the read-out image on the app one at a time and does not read the file in the process, although it can perform basic functions on the AVD Android emulator. Therefore, the handler, message with the thread and other Android message mechanism, the completion of the reading process, and the use of the GridView to read the picture displayed. Improve this memory card picture reader, the specific effect is as follows, basically can be comparable to some of the Android system comes with the library bar ... It's just a matter of sorting the folder.


At first, in the process of reading, there is the display of the reading progress, the specific read to which folder. This is very meaningful for large memory cards, my 8G memory card pro-test, only 30 seconds to complete the read.

Then, use the grid view to display the picture. Click on the picture to see a larger image of the picture, with the path to the picture.

You can exit in the upper-right corner of the app.

Of course, this app also completes the monitoring of the return key. The return key can also be exited. This is in the "Android" a variety of pop-up boxes and the menu keys, return key monitoring (click to open the link) has said, here no longer repeat.

1, first modify the Res\values\strings.xml, set the individual characters, as follows. Author or something, please ignore these details!

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <string name= "app_name" > Memory card Picture Viewer </ string>    <string name= "Menu_author" >yongh701</string>    <string name= "Menu_exit" > Exit </string>    <string name= "img_description" > Large map </string>    <string name= "View_button1" > Back </string></resources>
2, after modifying the menu character file Res\menu\main.xml as follows, a configuration to Mainactivity.java, this in the "Android" date picker, Time Picker and menu (click Open link) has been said. Don't repeat it here.

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" >    <item        android:id= "@+id/menu_ Exit "        android:title=" @string/menu_exit "/>    <item android:title=" @string/menu_author "/></menu >
3, then complete androidmanifest.xml modification, request the system to the app to give SDcard read and write permission. At the same time, because the app looks at the big picture with another activity, here at the same time register here to see the larger image of the viewactivity, the file is modified as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.sdcard_read_all "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" android.perm Ission. Read_external_storage "/> <!--require data access to SDcard and <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> <!--required to write data to SDcard permissions--<application Android:allowbac Kup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@styl E/apptheme "> <activity android:name=" Com.sdcard_read_all. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android. Intent.category.LAUNCHER "/> </intent-filter> </activity> <activity Android:name= "Com.sdcard_read_all. Viewactivity "android:label=" @string/img_description "> <!--registration viewactivity--&LT;/ACTIVITY&G    T </application></manifest>
4, in fact, after the process, and "Android" Image resource access and web format picture browser (click the Open link) is the same. Modify the mainactivity layout file First Res\layout\activity_ Main.xml, lay out a grid layout gridview, of course, also decorate a textview, which is used to display the read information before the read is completed, and the file is modified as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <textview        Android:id= "@+id/textview1"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:textsize= "36sp"/>    <gridview        android:id= "@+id/gridview1"        android:layout_width= " Match_parent "        android:layout_height=" match_parent "        android:numcolumns=" 2 ">    </GridView> </LinearLayout>
5, at the same time in res\layout\ create a view large map of the viewactivity layout file activity_view.xml, here and "Android" gallery-style picture browser, Use Horizontalscrollview instead of Gallery,onclicklistener parameter passing (click to open link) in the same vein, create a new linear sub-layout linearlayout under a vertical scrolling layout. This way, you don't have to worry about more than one screen of the component to achieve scrolling. This is done by the linear layout of the scroll bar. The three components are all stained with the screen width, and the IDs are given separately, and the corresponding values are given in a moment by Viewactivity.java. Where picture view ImageView is configured with the Adjustviewbounds and ScaleType, so that it is automatically scaled smaller. android:contentdescription= "@string/img_description" is a description of the picture, not given, eclipse will appear warning.

<scrollview xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "match_parent" android:scrollbars= "vertical" > <linearlayout android:layout_width             = "Match_parent" android:layout_height= "wrap_content" android:orientation= "vertical" > <textview Android:id= "@+id/textview1" android:layout_width= "Match_parent" android:layout_height= "W            Rap_content "android:textsize=" 24sp "/> <imageview android:id=" @+id/imageview1 " Android:layout_width= "Match_parent" android:layout_height= "Wrap_content" Android:adjustviewbound S= "true" android:scaletype= "Centerinside" android:paddingtop= "10DP" Android:paddingbottom = "10DP" android:contentdescription= "@string/img_description"/> <button android:id= "@+i D/button1 "Android:Layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "@string/view_button1" Android:textsize= "24sp"/> </LinearLayout></ScrollView>

6, under Src\ Current project package (here is Com.sdcard_read_all), such as "Android" between multiple activity using bundle Transfer value (click Open link), like, Create a new Viewactivity.java that inherits Android.app.Activity. The inside code is as follows:

Package Com.sdcard_read_all;import Android.app.activity;import Android.content.intent;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.view.keyevent;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;import Android.widget.textview;public class ViewActivity Extends Activity {private TextView textview1;private ImageView imageview1;private Button button1; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ view);//Get Component TextView1 = (TextView) Findviewbyid (r.id.textview1); imageView1 = (ImageView) Findviewbyid ( R.ID.IMAGEVIEW1); button1 = (Button) Findviewbyid (r.id.button1);//Get the Mainactivity pass the picture path, the corresponding processing. Intent Intent = Getintent (); Bundle bundle = Intent.getextras (); String Imgpath = bundle.getstring ("Imgpath"); Textview1.settext ("Picture path:" + Imgpath); Bitmap BM = Bitmapfactory.decodefile (Imgpath); Imageview1.setimagebitmap (BM);//button return event Button1.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View arg0) {finish ();}}); Monitoring of physical Buttons @overridepublic boolean onKeyDown (int keycode, keyevent event) {switch (keycode) {case Keyevent.keycode_back: Finish ();//close the activity. break;} Return Super.onkeydown (KeyCode, event);}}
7, completed the View large image viewactivity, is our finale mainactivity,mainactivity is also the core of the entire program, the code is as follows. The code is divided into five parts: 1, traversing the SDcard method, 2, loading the image of the cache tool method, the two methods with "Android" read all the pictures on the SDcard card and show that the reading process has a progress bar display "(Click Open link) is the same. 3, program execution OnCreate method, 4, the app's menu, this "Android" date picker, Time Picker and menu (click Open link) has said. 5, the physical button monitoring, this can refer to the "Android" a variety of pop-up boxes and the menu key, return key monitoring (click to open the link).

The entrance to the program is also the OnCreate method for other Android programs. The execution of the program will be divided into two parts:

1, read, open a read, using the thread messaging mechanism of Android, constantly in the update textView1. This is the same as the "Android" progress bar and thread of the message processing (click to open the link) is actually the same. The only way to complete the update, through the thread messaging mechanism of Android, not the app will appear in the freezing thread. The Android system automatically dispatches and allocates resources to the threads on the program. Before the program because the processing of the thread is not good, causing the reading of the large memory card will be stuck. Now it's okay to read a memory card through the thread messaging mechanism of Android!

2, read, and "Android" Image resource access and web format picture browser (click to open the link) Similarly, the use of the adapter and grid view, to display all the pictures. This is because the grid view comes with an adapter that automatically allocates resources, and therefore consumes less system resources. At the same time, the grid view is given listening, click on the picture to pass the picture path, and open the view large image viewactivity.

Package Com.sdcard_read_all;import Java.io.file;import Java.util.arraylist;import android.os.bundle;import Android.os.environment;import Android.os.handler;import Android.os.message;import Android.view.KeyEvent;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.ViewGroup;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.baseadapter;import Android.widget.gridview;import Android.widget.imageview;import Android.widget.imageview.scaletype;import Android.widget.textview;import Android.app.activity;import Android.content.intent;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;public Class Mainactivity extends Activity {private TextView textview1;private GridView gridview1;private static Handler handler;//thread The Message Processor//is used to hold all picture paths on the SDcard card public static arraylist<string> Dirallstrarr = new arraylist<string> ();// class public static void Dirall (file) used to traverse all files on the SDcard card Dirfile) throws Exception {if (dirfile.exists ()) {File files[] = Dirfile.listfiles (); for (File file:files) {String file Name = File.getname (); String FilePath = File.getpath ();//Read file path, send as information to handler for processing message msg = new Message (); msg.obj = "reading:" + Filepath;hand Ler.sendmessage (msg); if (File.isdirectory ()) {//except SDcard on Android this folder. if (!filename.endswith ("Android")) {//If a folder is encountered, it is called recursively. Dirall (file);}} else {//If the picture file is pressed into the array if (Filename.endswith (". jpg") | | | Filename.endswith (". jpeg") | | filename.endswith (". bmp") | | Filename.endswith (". gif") | | Filename.endswith (". png")) {if (Dirfile.getpath (). EndsWith (File.separator)) {Dirallstrarr.add (Dirfile.getpath () + File.getname ());} else {Dirallstrarr.add (Dirfile.getpath () + file.separator+ file.getname ());}}}}} Picture loaded Cache tool class, using the method of Android, compressed picture according to size public static bitmapfactory.options getheapopts (file file) {Bitmapfactory.options opts = new Bitmapfactory.options ();//The larger the number read out the memory must be smaller, or it will always overflow if (File.length () < 20480) {//0-20kopts.insamplesize = 1;//ThisThe size of the zoom, the more the number is scaled more powerful} else if (File.length () < 51200) {//20-50kopts.insamplesize = 2;} else if (File.length () < 30  7200) {//50-300kopts.insamplesize = 4;} else if (File.length () < 819200) {//300-800kopts.insamplesize = 6;} else if (File.length () < 1048576) {//800-1024kopts.insamplesize = 8;} else {opts.insamplesize = 10;} return opts;} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);//Get Component TextView1 = (TextView) Findviewbyid (r.id.textview1); gridView1 = (GridView) Findviewbyid (r.id.gridview1);//The grid view is therefore gridview1.setvisibility (view.invisible) before the thread starts, and/* threads that traverse all the folders under SDcard start * /thread Readsdcard = new Thread () {private String Sdpath = Environment.getexternalstoragedirectory (). GetAbsolutePath () ;//Get sdcard root path private File dirfile = new file (sdpath);p ublic void Run () {try {dirall (dirfile);//traverse SDcard all folders//after completion , before the thread itself dies, send a "0" flag message to Handlermessage msg = new Message (); msg.obj = "0";Handler.sendmessage (msg);} catch (Exception e) {e.printstacktrace ();}};}; Textview1.setvisibility (view.visible); Readsdcard.start ();//thread start, default does not start. /* Traverse all folder end of SDcard *///keep on receiving linear message, according to the message, processing//With the beginning of the thread Readsdcard, with the death of the die, and the thread is a pair. Handler = new Handler (new Handler.callback () {//write this, do not eject any warning of the leak @overridepublic Boolean handlemessage (Message msg) { Textview1.settext (Msg.obj + ""), if (Msg.obj.equals ("0")) {//After completion of reading textview1.setvisibility (view.gone);// Hide Read Information gridview1.setvisibility (view.visible);//Display grid view}return false;}); /Grid View Adapter Baseadapter baseadapter = new Baseadapter () {@Overridepublic view getView (int position, view Convertview, Viewgro Up arg2) {ImageView imageview1;if (Convertview = = null) {ImageView1 = new ImageView (mainactivity.this); Imageview1.setadjustviewbounds (TRUE);//auto-scale to aspect ratio imageview1.setscaletype (scaletype.center_inside);// Set picture to maintain aspect ratio display imageview1.setpadding (5, 5, 5, 5);} else {imageView1 = (ImageView) Convertview;} Load the picture into the grid view string FilePath = Dirallstrarr.get (position); File file = new file (FilePath); Bitmap BM = bitmapfactory.decodefile (filepath,getheapopts (file)); Imageview1.setimagebitmap (BM); return imageView1;} Gets the current option @overridepublic long getitemid (int position) {return position;} @Overridepublic Object getItem (int position) {return position;} Gets the quantity @overridepublic int GetCount () {return dirallstrarr.size ();}; Gridview1.setadapter (baseadapter);//link the adapter to the grid view Gridview1.setonitemclicklistener (new Onitemclicklistener () {// Click on any picture of the grid assembly @overridepublic void Onitemclick (adapterview<?> arg0, View arg1,int position,// Position for clicked Idlong Arg3) {Intent Intent = new Intent (mainactivity.this,viewactivity.class);//Activate Viewactivitybundle bundle = new Bundle (); Bundle.putstring ("Imgpath", dirallstrarr.get (position));// Pass the ID of the clicked picture to Viewactivityintent.putextras (bundle); startactivity (intent);});} You create a method for the menu without the method, and the menu is not set in the upper-right corner. @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Sets the Menu interface to Res\menu\menu.xmlgetmenuinflater (). Inflate ( R.menu.main, menu); RetuRN true;} Handle Menu Event Public boolean onoptionsitemselected (MenuItem Item) {//Gets the Id,int item_id = Item.getitemid () of the currently selected MenuItem; Switch (item_id) {//sets the method to be executed for the menu subkey with ID menu_exit. Case R.id.menu_exit:system.exit (0);//End program break;} return true;} Monitoring of physical Buttons @overridepublic boolean onKeyDown (int keycode, keyevent event) {switch (keycode) {case Keyevent.keycode_back: Finish ();//close the activity. break;} Return Super.onkeydown (KeyCode, event);}}
The entire production process as shown above, I also uploaded a copy of the Ecllipse, in ADT Writing source code, we are interested to download to see:

Android read all images on SD card (click to open link)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" Memory card picture reader, gallery app

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.