packagecom.example.testresponsecache;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importandroid.os.AsyncTask;importandroid.os.Bundle;importandroid.annotation.SuppressLint;importandroid.app.Activity;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.util.Log;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ImageView;publicclassMainActivityextendsActivity{privatefinalStringTAG=getClass().getSimpleName();ImageViewimg;Buttonmsg;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);img=(ImageView)this.findViewById(R.id.img);msg=(Button)this.findViewById(R.id.msg);msg.setOnClickListener(newOnClickListener(){@OverridepublicvoidonClick(Viewv){newInternetTask().execute();}});}@SuppressLint("NewApi")classInternetTaskextendsAsyncTask<String,String,Boolean>{Bitmapbitmap;StringjsonStr;@SuppressLint("NewApi")@OverrideprotectedvoidonPostExecute(Booleanresult){super.onPostExecute(result);img.setImageBitmap(bitmap);msg.setText(jsonStr);}@OverrideprotectedBooleandoInBackground(String...params){// Test download imagetry{URLurl=newURL("http://jasoncheng.tw/1.png");HttpURLConnectionconn=(HttpURLConnection)(url.openConnection());conn.connect();InputStreamis=conn.getInputStream();BitmapFactory.Optionsops=newBitmapFactory.Options();bitmap=BitmapFactory.decodeStream(is,null,ops);is.close();conn.disconnect();}catch(Exceptione){Log.e(TAG,e.getMessage(),e);}// Test download JSON datatry{URLurl=newURL("http://jasoncheng.tw/1.json");HttpURLConnectionconn=(HttpURLConnection)(url.openConnection());conn.connect();BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream(),"UTF-8"));jsonStr=reader.readLine();InputStreamis=conn.getInputStream();is.close();conn.disconnect();}catch(Exceptione){Log.e(TAG,e.getMessage(),e);}returntrue;}}}
沒有留言:
張貼留言