Android SDcard realizes picture storage, networked download _android

Source: Internet
Author: User
Tags event listener save file

This article introduces the sdcard storage picture Download simple operation, share to everyone for your reference, the specific contents are as follows

Step--After adding network permissions to the configuration manifest

1, Res/layout interface layout

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"

  xmlns:tools= "http:// Schemas.android.com/tools "

  android:layout_width=" match_parent "

  android:layout_height=" Match_parent "

  android:orientation= "vertical" >



  <imageview

    android:id= "@+id/imageview"

    android:layout_ Width= "Wrap_content"

    android:layout_height= "wrap_content"/> <button android:id=

    "@+id/bt_" Download "

    android:layout_width=" wrap_content "

    android:layout_height=" wrap_content "

    android:text" = "Picture Download"

    android:onclick= "Image_download"/>



</LinearLayout>

2, there are 2 classes of one Operation SDcard File tool Class (Fileutil) another mainactivity class

Fileutil class

Operation SDcard's File tool class public class Fileutil {private static final String Cache_dir = Environment.getexternalstoragedirec



 Tory () + "/my_caches/images";

 private static int comp_jpg = 0;

private static int comp_png = 1;

 Determine if SDcard is mounted (whether there is sdcard) public static Boolean ismounted () {String state = Environment.getexternalstoragestate ();

 Return State.equals (environment.media_mounted); //Get the absolute path to the SDcard file root path public static String Getsdcard () {return environment.getexternalstoragedirectory (). GETABSO

 Lutepath ();

 //Get filename public static string getfilename (String URL) {return url.substring (Url.lastindexof ('/') + 1); 

 //Save File Method 1 public static void Sava1 (String url,byte[] Data {//To determine whether there is sdcard if (!ismounted ()) {return;

 ///have SDcard//determine if there is a cached folder file Dir = new file (Cache_dir);

 if (!dir.exists ()) {//No cache folder creation folder exists to save the file Dir.mkdirs ();

 ///Save the file data to sdcard filename = new file (dir,getfilename (URL)); try {fileoutputstream fos = new FileOutputStream (file);

 

 Fos.write (data);

 Fos.close ();

 catch (Exception e) {e.printstacktrace (); //Save File Method 2 public static void Sava2 (String url,bitmap bitmap,int format) {//To determine if there is a sdcard if (!ismounted ())

 {return;

 File dir = new file (Cache_dir);

 if (!dir.exists ()) {dir.mkdirs ();

 //write the file data to sdcard filename = new file (dir,getfilename (URL));

 try {fileoutputstream fos = new FileOutputStream (file); Write the picture file to the cache bitmap.compress (format = = comp_jpg?

 

 CompressFormat.JPEG:CompressFormat.PNG), MB, FOS);

 Fos.close ();

 catch (Exception e) {e.printstacktrace ();

 Read the picture public static Bitmap readimage (String URL) {if (!ismounted ()) {return null;

 File File = new file (cache_dir,getfilename (URL));

 if (file.exists ()) {return bitmapfactory.decodefile (File.getabsolutepath ());

 return null;

 //Empty cache directory public void Clearcaches () {File Dir = new File (cache_dir); file[] File_datas = Dir.listfiles ();

 for (File File:file_datas) {file.delete ();

 }

 }

 

}

Mainactivity class

public class Mainactivity extends activity {private ImageView ImageView;

 Private String URL = "Yun_qi_img/d1160924ab18972bf5f68cc8e0cd7b899f510ae7.gif";

 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

 

 Setcontentview (R.layout.activity_main);

 This.imageview = (ImageView) This.findviewbyid (R.id.imageview);

 

 Set default picture Imageview.setimageresource (R.drawable.ic_launcher);

 //Picture Download button Click event Listener public void Image_download (view view) {//Judge whether there is a local picture Bitmap Bitmap = fileutil.readimage (URL);

 if (bitmap!= null) {Imageview.setimagebitmap (bitmap);

 }else{//No pictures on the Send network request new Myasynctask (). Execute (URL); }//Networking tools Class public class Myasynctask extends Asynctask<string, Void, byte[]>{@Override protected byt

 E[] Doinbackground (String ... params) {HttpGet get = new HttpGet (params[0));

 HttpClient client = new Defaulthttpclient ();

 HttpResponse response; try {response = Client.executE (GET);

 if (Response.getstatusline (). Getstatuscode () = () {byte[] data = Entityutils.tobytearray (Response.getentity ());

 FILEUTIL.SAVA1 (Params[0], data);

 return data;

 } catch (Exception e) {e.printstacktrace ();

 return null;

 @Override protected void OnPostExecute (byte[] result) {Super.onpostexecute (result);

 if (result!= null) {Bitmap Bitmap = Bitmapfactory.decodebytearray (result, 0, result.length);

 Imageview.setimagebitmap (bitmap);
 }

 }

 

 }

}

The above is the entire contents of this article, I hope to learn more about Android software programming help.

Related Article

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.