Androidは非同期で画像をダウンロードし、キャッシュ画像を現地のDEMOに詳細に説明します。


Androidの開発において、私たちはよくこのような要求を持っています。サーバーからxmlまたはJSONタイプのデータをダウンロードします。この中にはいくつかの画像リソースが含まれています。このデモはこの要求をシミュレートして、インターネットからXMLリソースをロードします。画像を含めて、私たちが行う解析XMLの中のデータは、ローカルのcacheディレクトリにキャッシュします。そしてカスタムAdapterでLIstViewに充填します。demoの運行効果は次の図を参照してください。

このデモを通して、少し勉強したいです。
1.どのようにXMLを解析しますか?
2.demoで使ったキャッシュ画像を地元の仮ディレクトリに送るという考えはどうですか?
3.Async Task類の使用は、非同期のデータをロードするためにはスレッドを開けなければならないが、スレッドを開いている時にはスレッドの数をうまくコントロールできない場合があり、スレッドの数が大きいと携帯電話はすぐにカードに殺されます。ここではAyncs Task類を使ってこの問題を解決します。この種類の中にはスレッド池の技術が封入されています。これにより、あまり多くのスレッドを開いても多くのリソースが消費されないことを保証します。
4.本デモの中のHandler類の使用状況5.カスタムadapperの使用
以下はデモの中のActivityです。

public class MainActivity extends Activity { 
 protected static final int SUCCESS_GET_CONTACT = 0; 
 private ListView mListView; 
 private MyContactAdapter mAdapter; 
 private File cache; 
 private Handler mHandler = new Handler(){ 
  public void handleMessage(android.os.Message msg) { 
   if(msg.what == SUCCESS_GET_CONTACT){ 
    List<Contact> contacts = (List<Contact>) msg.obj; 
    mAdapter = new MyContactAdapter(getApplicationContext(),contacts,cache); 
    mListView.setAdapter(mAdapter); 
   } 
  }; 
 }; 
 @Override 
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main); 
  mListView = (ListView) findViewById(R.id.listview); 
  //      ,              , 
  cache = new File(Environment.getExternalStorageDirectory(), "cache"); 
  if(!cache.exists()){ 
   cache.mkdirs(); 
  } 
  //    , UI           ,          
  new Thread(){ 
   public void run() { 
    ContactService service = new ContactService(); 
    List<Contact> contacts = null; 
    try { 
     contacts = service.getContactAll(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    //     Message      ,        , 
    //Handler   sendMessage()            ,      UI       
    Message msg = new Message(); 
    msg.what = SUCCESS_GET_CONTACT; 
    msg.obj = contacts; 
    mHandler.sendMessage(msg); 
   }; 
  }.start(); 
 } 
 @Override 
 protected void onDestroy() { 
  super.onDestroy(); 
  //     
  File[] files = cache.listFiles(); 
  for(File file :files){ 
   file.delete(); 
  } 
  cache.delete(); 
 } 
} 
Activityでは、以下の点に注意してください。
1.キャッシュディレクトリを初期化しました。このディレクトリはアプリケーションが開いたら作成し、キャッシュ画像を準備して、ここでデータをSDCardに保存してください。
2.サーバーにデータをロードするには、この時間がかかります。スレッドを開いてデータをロードし、ローディングが完了したら、非同期のUIスレッドを更新して、Handlerメカニズムを利用して、この問題をうまく解決できます。
3.最後にアプリケーションを終了する時は、キャッシュディレクトリとディレクトリ内のデータを削除し、携帯電話に多くのゴミファイルを作らないようにします。
次はサービス類です。

public class ContactService { 
 /* 
  *           
  */ 
 public List<Contact> getContactAll() throws Exception { 
  List<Contact> contacts = null; 
  String Parth = "http://192.168.1.103:8080/myweb/list.xml"; 
  URL url = new URL(Parth); 
  HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
  conn.setConnectTimeout(3000); 
  conn.setRequestMethod("GET"); 
  if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
   InputStream is = conn.getInputStream(); 
   //           XmlPullParser     
   contacts = xmlParser(is); 
   return contacts; 
  } else { 
   return null; 
  } 
 } 
 //            ,              
 private List<Contact> xmlParser(InputStream is) throws Exception { 
  List<Contact> contacts = null; 
  Contact contact = null; 
  XmlPullParser parser = Xml.newPullParser(); 
  parser.setInput(is, "UTF-8"); 
  int eventType = parser.getEventType(); 
  while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) { 
   switch (eventType) { 
   case XmlPullParser.START_TAG: 
    if (parser.getName().equals("contacts")) { 
     contacts = new ArrayList<Contact>(); 
    } else if (parser.getName().equals("contact")) { 
     contact = new Contact(); 
     contact.setId(Integer.valueOf(parser.getAttributeValue(0))); 
    } else if (parser.getName().equals("name")) { 
     contact.setName(parser.nextText()); 
    } else if (parser.getName().equals("image")) { 
     contact.setImage(parser.getAttributeValue(0)); 
    } 
    break; 
   case XmlPullParser.END_TAG: 
    if (parser.getName().equals("contact")) { 
     contacts.add(contact); 
    } 
    break; 
   } 
  } 
  return contacts; 
 } 
 /* 
  *         ,               ,                
  *    path       
  */ 
 public Uri getImageURI(String path, File cache) throws Exception { 
  String name = MD5.getMD5(path) + path.substring(path.lastIndexOf(".")); 
  File file = new File(cache, name); 
  //             ,          
  if (file.exists()) { 
   return Uri.fromFile(file);//Uri.fromFile(path)          URI 
  } else { 
   //          
   URL url = new URL(path); 
   HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
   conn.setConnectTimeout(5000); 
   conn.setRequestMethod("GET"); 
   conn.setDoInput(true); 
   if (conn.getResponseCode() == 200) { 
    InputStream is = conn.getInputStream(); 
    FileOutputStream fos = new FileOutputStream(file); 
    byte[] buffer = new byte[1024]; 
    int len = 0; 
    while ((len = is.read(buffer)) != -1) { 
     fos.write(buffer, 0, len); 
    } 
    is.close(); 
    fos.close(); 
    //     URI   
    return Uri.fromFile(file); 
   } 
  } 
  return null; 
 } 
} 
Serivce類では、以下の点に注意してください。
1.HttpURLConnection=(HttpURLConnection)url.openConnection;リンクを取得して通信します。
2.XxmlPullPaser類を利用してXMLを解析し、データを対象にカプセル化する方法
3.getImageURI(String path,File cache)この方法は具体的に実現されます。
4.Uri.from File(file);この方法は直接に一つのUriに戻ることができます。
以下はカスタムAdapter類で、

public class MyContactAdapter extends BaseAdapter { 
 protected static final int SUCCESS_GET_IMAGE = 0; 
 private Context context; 
 private List<Contact> contacts; 
 private File cache; 
 private LayoutInflater mInflater; 
 //           
 public MyContactAdapter(Context context, List<Contact> contacts, File cache) { 
  this.context = context; 
  this.contacts = contacts; 
  this.cache = cache; 
  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
 } 
 @Override 
 public int getCount() { 
  return contacts.size(); 
 } 
 @Override 
 public Object getItem(int position) { 
  return contacts.get(position); 
 } 
 @Override 
 public long getItemId(int position) { 
  return position; 
 } 
 @Override 
 public View getView(int position, View convertView, ViewGroup parent) { 
  // 1  item,      
  // 2      
  // 3     item 
  View view = null; 
  if (convertView != null) { 
   view = convertView; 
  } else { 
   view = mInflater.inflate(R.layout.item, null); 
  } 
  ImageView iv_header = (ImageView) view.findViewById(R.id.iv_header); 
  TextView tv_name = (TextView) view.findViewById(R.id.tv_name); 
  Contact contact = contacts.get(position); 
  //         (    + Handler ) ---> AsyncTask 
  asyncloadImage(iv_header, contact.image); 
  tv_name.setText(contact.name); 
  return view; 
 } 
 private void asyncloadImage(ImageView iv_header, String path) { 
  ContactService service = new ContactService(); 
  AsyncImageTask task = new AsyncImageTask(service, iv_header); 
  task.execute(path); 
 } 
 private final class AsyncImageTask extends AsyncTask<String, Integer, Uri> { 
  private ContactService service; 
  private ImageView iv_header; 
  public AsyncImageTask(ContactService service, ImageView iv_header) { 
   this.service = service; 
   this.iv_header = iv_header; 
  } 
  //             
  @Override 
  protected Uri doInBackground(String... params) { 
   try { 
    return service.getImageURI(params[0], cache); 
   } catch (Exception e) { 
    e.printStackTrace(); 
   } 
   return null; 
  } 
  //      ui      
  @Override 
  protected void onPostExecute(Uri result) { 
   super.onPostExecute(result);  
   //         
   if (iv_header != null && result != null) { 
    iv_header.setImageURI(result); 
   } 
  } 
 } 
 /** 
  *               
  */ 
 /*private void asyncloadImage(final ImageView iv_header, final String path) { 
  final Handler mHandler = new Handler() { 
   @Override 
   public void handleMessage(Message msg) { 
    super.handleMessage(msg); 
    if (msg.what == SUCCESS_GET_IMAGE) { 
     Uri uri = (Uri) msg.obj; 
     if (iv_header != null && uri != null) { 
      iv_header.setImageURI(uri); 
     } 
    } 
   } 
  }; 
  //    ,                  ,               
  Runnable runnable = new Runnable() { 
   @Override 
   public void run() { 
    ContactService service = new ContactService(); 
    try { 
     //  URI                URI 
     Uri uri = service.getImageURI(path, cache); 
     Message msg = new Message(); 
     msg.what = SUCCESS_GET_IMAGE; 
     msg.obj = uri; 
     mHandler.sendMessage(msg); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
   } 
  }; 
  new Thread(runnable).start(); 
 }*/ 
}
カスタムAdapterでは、AyncImageTaskはAync Taskクラスを継承しています。AyncTaskはAndroidでは非同期的なタスクを行うためによく使われているクラスです。スレッドプールはカプセル化されています。詳しくは後でBlogを貼り付けます。
以下はサーバーから取得して解析したXmlファイルです。

<?xml version="1.0" encoding="UTF-8"?> 
<contacts> 
 <contact id="1"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/mymyweb/images/1.gif"/> 
 </contact> 
 <contact id="2"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/2.gif"/> 
 </contact>  
 <contact id="3"> 
  <name>   </name> 
  <image src="http://192.168.1.103:8080/myweb/images/3.gif"/> 
 </contact>   
 <contact id="4"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/4.gif"/> 
 </contact>   
 <contact id="5"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/5.gif"/> 
 </contact> 
 <contact id="6"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/6.gif"/> 
 </contact>  
 <contact id="7"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/7.gif"/> 
 </contact>   
 <contact id="8"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/8.gif"/> 
 </contact>   
 <contact id="9"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/9.gif"/> 
 </contact> 
 <contact id="10"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/10.gif"/> 
 </contact>  
 <contact id="11"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/11.gif"/> 
 </contact>   
 <contact id="12"> 
  <name>dylan</name> 
  <image src="http://192.168.1.103:8080/myweb/images/12.gif"/> 
 </contact>   
 <contact id="13"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/13.gif"/> 
 </contact> 
 <contact id="14"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/14.gif"/> 
 </contact>  
 <contact id="15"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/15.jpg"/> 
 </contact>   
 <contact id="16"> 
  <name>   </name> 
  <image src="http://192.168.1.103:8080/myweb/images/16.jpg"/> 
 </contact>  
 <contact id="17"> 
  <name>   </name> 
  <image src="http://192.168.1.103:8080/myweb/images/17.jpg"/> 
 </contact>   
 <contact id="18"> 
  <name>  </name> 
  <image src="http://192.168.1.103:8080/myweb/images/18.jpg"/> 
 </contact>  
</contacts>
本デモでは、セキュリティのためにダウンロードしたピクチャのファイル名をMD 5に暗号化しました。下にはMD 5に暗号化されたコードがあります。

public class MD5 { 
 public static String getMD5(String content) { 
  try { 
   MessageDigest digest = MessageDigest.getInstance("MD5"); 
   digest.update(content.getBytes()); 
   return getHashString(digest); 
  } catch (NoSuchAlgorithmException e) { 
   e.printStackTrace(); 
  } 
  return null; 
 } 
 private static String getHashString(MessageDigest digest) { 
  StringBuilder builder = new StringBuilder(); 
  for (byte b : digest.digest()) { 
   builder.append(Integer.toHexString((b >> 4) & 0xf)); 
   builder.append(Integer.toHexString(b & 0xf)); 
  } 
  return builder.toString(); 
 } 
} 
以上、Contact.javaというdoman類を省略しました。このdemoを通じて、Androidでは常に非同期的なタスクの処理が必要であることが分かります。だから、私たちは自分で手動でスレッドを開いたり、handlerメカニズムを使ったり、AyncTask類などの手段でアプリケーションの性能を保証します。
以上は小编が绍介したAndroid非同期に画像をダウンロードし、现地のDEMOにキャッシュします。皆さんに助けてほしいです。もし何か疑问があれば、メッセージをください。小编はすぐに返事します。ここでも私たちのサイトを応援してくれてありがとうございます。