Implementation of Image Library encapsulation method by Android programming _android

Source: Internet
Author: User
Tags static class

The example of this article is about the packaging method of the Android programming implementation Picture Library. Share to everyone for your reference, specific as follows:

When you are doing Android applications, you often get pictures from the Internet, but you get them from the web, but it's not faster if you have local image data from local data. Some of them have encountered this problem in their work so a mapping relationship between a URL and a local image is obtained first from the region if the local is not retrieved from the network This method takes the multithreading question to welcome everybody to discuss together!

public class Picturelibrary {/* * Picture library operation/file file;
 URL url;
 HttpURLConnection Conn;
 InputStream is;
 FileOutputStream Fos;
 Private lock lock = new Reentrantlock ();
 Private Condition Downfile = Lock.newcondition ();
  Downloading data to local operations via a URL private string tolocalfile (String strurl) {string fileName = Utils.getfilename (strURL);
  String path = environment.getexternalstoragedirectory () + "/" + Ecologicaltourism.file_path + "/images/" + fileName;
 return path;
  ///Download data to local temporary files by URL private string tolocalfiletemp (String strurl) {string s = utils.getfilename (strURL);
  String fileName = s+ "Temp"; String Path_url = environment.getexternalstoragedirectory () + "/" + Ecologicaltourism.file_path + "/tempimages/" + fil
  ename;
 return path_url; } * * Save pictures to local, and returns a local URL (this function is blocked) * main * @ parameter: strURL, the parameter is the URL of the picture. Return value: The image in the local SD card staging location * function is responsible for the image from the Internet, there is local storage, and return Returns the locally stored file path for direct use by the caller.
  If the file already exists locally, return * If the file is not local, download directly from the server, blocking the function. */public string GETREADSD (string strURL) {log.i ("test"), "get the address of the network is:" + strurl); String strlocalfile = Tolocalfile (strURL); K: Converts the server URL to a local URL String strlocalfiletemp = tolocalfiletemp (strURL);
   K: Converts the server URL to a local temporary URL while (true) {File File = new file (strlocalfile);
   LOG.I ("Test", "Local file is:" + strlocalfile);
   File Tfile = new file (strlocalfiletemp);
   LOG.I ("Test", "Temporary file is:" + strlocalfiletemp);
   1 locked Lock.lock ();
    if (file.exists ()) {//2if local file exists//unlock//Return local path Lock.unlock ();
    LOG.I ("Test", "return to Local Path:" + file);
   return strlocalfile;
    else if (tfile.exists ()) {//if the corresponding staging file exists//unlock lock.unlock ();
    try {//Sleep downfile.await ();
     catch (Exception e) {e.printstacktrace ();
    LOG.I ("Test", "E appears abnormal 1" + e);
    } else {try {///create the corresponding staging file Tfile.createnewfile ();
    catch (IOException e) {log.i ("test", "E appears exception 2" + E);
    }//Unlock lock.unlock ();
Download the contents of the file to the staging file DownURL2 (strURL, strlocalfile);    Lock Lock.lock ();
    Modify staging file name is local filename tfile.renameto (file);
   Unlock Lock.unlock ();
  }} private void DownURL2 (string strurl, String strlocalfiletemp) {//TODO auto-generated method stub URL url;
   try {url = new URL (strurl);
   HttpURLConnection conn = (httpurlconnection) url.openconnection ();
   Conn.setconnecttimeout (5000);
   Conn.setrequestmethod ("get");
   Conn.setdoinput (TRUE);
     if (Conn.getresponsecode () = () {InputStream is = Conn.getinputstream ();
     FileOutputStream fos = new FileOutputStream (strlocalfiletemp);
     byte[] buffer = new byte[1024];
     int len = 0;
     while (len = is.read (buffer))!=-1) {fos.write (buffer, 0, Len);
     } is.close ();
     Fos.close ();
  Returns a URI object} catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace ();
  catch (Protocolexception e) {//TODO auto-generated catch block E.printstacktrace (); catch (IOException e) {
   TODO auto-generated Catch block E.printstacktrace ();
  }/* * blocked download URL to file ToFile/private Boolean Downurl (String strurl, string tofile) {URL url;
   try {url = new URL (strurl);
   HttpURLConnection Httpurl = (httpurlconnection) URL. OpenConnection ();
   Httpurl.setrequestmethod ("get"); int fileSize = Httpurl.getcontentlength ()//File size Httpurl.disconnect ()//close connection int threadsize = 6;//default setting of 6 threads THR Eadsize = fileSize% Threadsize = = 0?
   Threadsize:threadsize + 1; int currentsize = filesize/threadsize; Per thread Download size String Dowloadir = environment.getexternalstoragedirectory () + "/" + Ecologicaltourism.file_path + "/I
   Mages/";
   File dir = new file (Dowloadir);
   if (!dir.exists ()) {dir.mkdirs ();
   File File = new file (dir, tofile);
   Randomaccessfile randomfile = new Randomaccessfile (file, rw); Randomfile.setlength (fileSize)//Specifies the size of the file for (int i = 0; i < threadsize; i++) {int startposition =I * currentsize;//where each thread starts writing to the file randomaccessfile threadfile = new Randomaccessfile (file, rw);
    LOG.I ("Syso", "ToFile content is:" + tofile);
    Threadfile.seek (startposition);
   New Downloadthread (i, CurrentSize, threadfile, startposition, URL). Start ();
   } catch (Exception e) {e.printstacktrace ();
  LOG.I ("Syso", "Download Download failed" + e);
 return true; /** * Implementation thread download */private static class Downloadthread extends Thread {@SuppressWarnings ("unused") private int threadid;//thread number private int currentsize;//the size of each thread private randomaccessfile threadfile; Each thread is written to the file class private int startposition;//the location of each thread to begin writing to the file at the private URL url;  Network address public downloadthread (int threadId, int currentsize, randomaccessfile threadfile, int startposition, URL url)
   {this.threadid = threadId;
   This.currentsize = CurrentSize;
   This.threadfile = Threadfile;
   This.startposition = startposition;
  This.url = URL; public void Run () {try {HttpURLConnection Httpurl = (httpurlconnection) URL. OpenConnection ();
    Httpurl.setrequestmethod ("get"); Httpurl.setrequestproperty ("Range", "bytes=" + startposition + "-");//Specifies the location of the server InputStream is = Httpurl.getinpu
    Tstream ();
    byte[] data = new byte[1024];
    int len =-1;
    int threadfilesize = 0; while (Threadfilesize < currentsize) && (len = is.read (data)!=-1)) {threadfile.write (data, 0,
     Len);
    Threadfilesize = Len;
    } httpurl.disconnect ();
   Is.close ();
   catch (Exception e) {e.printstacktrace (); /** * Get picture from this cache */public Bitmap Getbitmapfromcache (string ImageURL) {//String Bitmapname = Imageurl.subst 
  Ring (Imageurl.lastindexof ("/") + 1);
  String bitmapname = Utils.getfilename (ImageURL);
  File Cachedir = new file (environment.getexternalstoragedirectory () + "/" + Ecologicaltourism.file_path + "/images/");
  file[] Cachefiles = Cachedir.listfiles ();
  int i = 0; if (Null!=cachefiLes) {for (; i<cachefiles.length;i++) {if (Bitmapname.equals (Cachefiles[i].getname ())) {break; } if (I < cachefiles.length) {return bitmapfactory.decodefile (environment.getexternalstoragedirectory)
   + "/" + Ecologicaltourism.file_path + "/images/" + bitmapname);
 } return null;

 }

I hope this article will help you with your Android programming.

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.