"Android" memory card picture reader, Gallery app

Source: Internet
Author: User
Tags exit in
<span id="Label3"></p><p><p>The previous article "Android" read all the pictures on the SDcard card and show that the reading process has a progress bar display (click The open link) on the real machine test is very problematic. Memory overflow is often encountered. The condition of the Card-dead. Because of the memory on the real machine today, 2G is already very rare, basically 8G appearance.</p></p><p><p>The app is very unfriendly because it puts the read-out image on the app one at a time, and there is no file being read in the process, although the main function can be completed on the AVD Android Simulator.</p></p><p><p>therefore, the use of handler, message with the thread and other Android message Mechanism. Complete the read process, and use the GridView to read the picture Displayed. Improve this memory card picture reader, detailed effects such as the following, basically can be comparable to some of the Android system comes with the library bar ... It's just a list of categories ...</p></p><p><p><br></p></p><p><p>Start. During the Read process. There is a read progress display, which directory is read in Detail.</p></p><p><p>This is very meaningful for large memory cards. My 8G memory card is tested, only 30 seconds to complete the Read.</p></p><p><p>then, Use the grid view to display the Picture. Click on the image to see a larger image of the Picture. The path to the Picture.</p></p><p><p>You can exit in the top right corner of the app.</p></p><p><p></p></p><p><p>Of course, the app also finished monitoring the return key.</p></p><p><p>The return key can also be Exited.</p></p><p><p>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.</p></p><p><p>1, first change res\values\strings.xml, set each character, such as the Following. Author or something, Please ignore these details!</p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html"><?xml version= "1.0" encoding= "utf-8"?<p></p><p>><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 "> big picture </string> <string name=" view_button1 "> back </string></resources></p></pre></pre>2, After the Change menu character file Res\menu\main.xml for example, a configuration to mainactivity.java, which in the "Android" date picker, time Picker and menu (click open Link) has been said. Don't repeat it here.<p><p></p></p><p><p></p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html"><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 ></pre></pre>3, the subsequent completion of Androidmanifest.xml Changes. Requires the system to give SDcard read and write permission to this app. At the same time. As the app looks at the bigger picture, There's an activity, and here at the same time, check out the viewactivity of the big Picture. The file changes such as the Following:<p><p></p></p><p><p></p></p><pre name="code" class="html"><?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 "> &LT;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 "> <!--brochure VIEWACTIVITY--&LT;/ACTIVITY&G T </application></manifest></pre>4, in fact, after the process, and "Android" image resource access to the Web format picture browser (click The open Link) is the Same. First change mainactivity layout file res\layout\activity_main.xml, layout a grid layout gridview. of course, a TextView is arranged at the same time to be used before the reading is Complete. Displays the Read Information. After this file changes, for example, the following:<p><p></p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html"><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></pre></pre>5, at the same time in res\layout\ create a new view large map of the viewactivity layout file activity_view.xml. This is the same as "Android" Gallery-style picture browser, using Horizontalscrollview instead of Gallery,onclicklistener (click to open link). Just under a vertical scrolling Layout. Creates a new linear sub-layout Linearlayout. So you don't have to worry about more than one screen of the component to achieve scrolling results. This is done with the linear layout of the scroll bar. Three components are stained with the screen width, the same time to give the id, a moment by Viewactivity.java to give the corresponding Value. In the picture view ImageView configuration adjustviewbounds and Scaletype. Make it self-scaling Small.<p><p></p></p><p><p>Android:contentdescription= "@string/img_description" is a descriptive narrative of the picture, not Given. Eclipse will appear with a warning.</p></p><p><p></p></p><pre name="code" class="html"><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></pre><p><p></p></p><p><p>6, under src\ current project package (here is com.sdcard_read_all). For example, "Android" uses bundles to pass values between multiple activity (click open link) to create a new Viewactivity.java that inherits Android.app.Activity. The inside code is for example the Following:</p></p><p><p></p></p><pre name="code" class="java">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, do 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);}}</pre>7, finished looking at the big picture viewactivity, is our finale mainactivity,mainactivity is also the core of the entire program, code such as the Following. The code is structured into five Parts: 1. The method of traversing Sdcard. 2, loading the image of the cache tool method, both methods and "Android" read all the pictures on the SDcard card and Display. The read process has a progress bar display (click The open link) is the Same.<p><p></p></p><p><p>3, The program Operation OnCreate method, 4, the App's menu, this "Android" date picker, time Picker and menu (click open Link) has SAID.</p></p><p><p>5, the monitoring of the physical keys. This can be a reference to the "Android" a variety of pop-up boxes and the menu keys, return key monitoring (click the open link).</p></p><p><p></p></p><p><p>The entrance to the program is the same as the OnCreate method for other Android Programs.</p></p><p><p>The operation of the program will be divided into two parts:</p></p><p><p>1, Read Time. Open a read to take advantage of the thread messaging mechanism of ANDROID. Keep on updating textView1. This is in fact the same as the "Android" progress bar-to-thread message processing (click to open link). Only this can be updated, through the thread messaging mechanism of android, not the app will appear in the freezing thread. The Android system will proactively schedule and allocate resources to the threads on the program ITSELF.</p></p><p><p>The previous program due to bad processing of the thread, resulting in 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!</p></p><p><p></p></p><p><p>2, read completed, and "Android" image resources access to the Web format picture browser (click The open link) the Same. Use the adapter and grid view to display all the Pictures. This is because the grid view comes with an adapter that allocates resources on its own initiative 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.</p></p><p><p></p></p><pre name="code" class="java">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 directory. If (!filename.endswith ("Android")) {//assumes that the directory is encountered recursively Called.<p><p> </p> </p><p>Dirall (file);}} else {//assuming that 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 image 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;//this means the size of the scale, the more the number is scaled more and more, the more it is (file.length () < 51200) {//20-50kopts.insamplesize = 2;} else if (file.length () < 307200) {//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);// Gets the component TextView1 = (TextView) Findviewbyid (r.id.textview1); gridView1 = (GridView) Findviewbyid (r.id.gridview1);//before the thread Starts. The grid view is therefore gridview1.setvisibility (view.invisible);/* threads that traverse all sdcard directories start */thread readsdcard = new Thread () {private String Sdpath = environment.getexternalstoragedirectory (). getabsolutepath ();//gets The root path of the sdcard private File dirfile = new File (sdpath);p ublic void run () {try {dirall (dirfile);//after traversing all of the Sdcard's directories//complete, a "0" flag message is sent before the thread itself Dies. Give handlermessage msg = new Message (); msg.obj = "0"; handler.sendmessage (msg);} Catch (Exception e) {e.printstacktrace ();}};}; Textview1.setvisibility (view.visible); readsdcard.start ();//thread starts, default does not start.</p><p>/* Traverse sdcard All directories end *///keep receiving linear messages, depending on the Message. Processing//occurs with the opening beginning of the thread Readsdcard. Die with their death. is a pair with a thread. Handler = new handler (new handler.callback () {//write this. Do not eject any leaks warning @overridepublic boolean handlemessage (Message msg) {textview1.settext (msg.obj + ""); if (msg.obj.equals ("0 ) {///after 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);//self-scaling to the 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 the random picture of the grid component when the event @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);});} There is no method for creating a Menu. 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) {//set the method to run for the menu subkey with ID menu_exit. Case R.id.menu_exit:system.exit (0);//end Program break;} Return true;} Listener for Physical button @overridepublic boolean onKeyDown (int keycode, keyevent event) {switch (keycode) {case keyevent.keycode_ Back:finish ();//close the Activity. break;} return Super.onkeydown (keycode, event);}}</p></pre>Throughout the production process as seen above, I also uploaded a copy of the ecllipse, in ADT writing source code, We are interested to be able to download to see:<p><p></p></p><p><p>Android read all images on SD card (click to open Link)<br></p></p> <p><p>"Android" memory card picture reader, Gallery app</p></p></span>

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.