PackageCom.example.demo1;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportCom.tiffdecoder.TiffDecoder;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.os.AsyncTask;ImportAndroid.widget.ImageView; Public classDownloadimagestaskextendsAsynctask<object, Void, bitmap>{ImageView ImageView=NULL; Activity Activity=NULL; @OverrideprotectedBitmap doinbackground (Object ... parameters) { This. ImageView = (ImageView) parameters[0]; This. Activity = (activity) parameters[1]; Try { returndownload_image (String) Imageview.gettag ()); } Catch(IOException e) {e.printstacktrace (); } return NULL; } @Overrideprotected voidOnPostExecute (Bitmap result) {if(Result! =NULL) Imageview.setimagebitmap (result); } PrivateBitmap download_image (String URL)throwsIOException {File file=downloadFile (URL); Tiffdecoder.nativetiffopen (File.getpath ()); int[] pixels =tiffdecoder.nativetiffgetbytes (); Bitmap Mbitmap=bitmap.createbitmap (pixels, Tiffdecoder.nativetiffgetwidth (), Tiffdecoder.nativetiffgetheight (), Bitmap.Config.ARGB_8888); Tiffdecoder.nativetiffclose (); returnMbitmap; } PrivateFile downloadFile (String strurl)throwsioexception {URL url=NewURL (strURL); HttpURLConnection URLConnection=(HttpURLConnection) url.openconnection (); Urlconnection.setrequestmethod ("GET"); Urlconnection.setdooutput (true); Urlconnection.connect (); File File= File.createtempfile ("MyFile", ". tif", This. Activity.getcachedir ()); if(File.exists ()) File.delete (); File.createnewfile (); FileOutputStream FileOutput=Newfileoutputstream (file); InputStream InputStream=Urlconnection.getinputstream (); byte[] buffer =New byte[1024]; intBufferlength = 0; while((Bufferlength = inputstream.read (buffer)) > 0) {fileoutput.write (buffer,0, bufferlength); } fileoutput.close (); returnfile; }}
Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). b Uild ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ()); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, Windowmanager.layoutparams . Flag_fullscreen); ImageView Image= (ImageView) This. Findviewbyid (R.id.image); Image.settag ("Http://xibei1-image.xxx.com/00006009b4673bbc-ff2a-49bd-91fe-764c01b2acce01.tif"); NewDownloadimagestask (). Execute (Image, This); }}
Android Asynchronous Download