十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Android应用中如何异步下载图片并将图片保存到本地DEMO中?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
通下面是demo中的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){ Listcontacts = (List ) 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 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(); } }