2016年11月6日日曜日

Android AsyncTask 异步任务下载图片并显示咋UI线程

Android AsyncTask 异步任务下载图片并显示咋UI线程



public class MainActivity extends AppCompatActivity {
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv = (ImageView) findViewById(R.id.imageView);
                DownImg di = new DownImg(MainActivity.this, iv);
                di.execute("url");
            }
        });
    }
}



public class DownImg extends AsyncTask<String, Integer, byte[]> {
    private ImageView iv;
    private int file_length;
    private Context context;
    protected ProgressDialog pd;

    public DownImg(Context context, ImageView iv) {
        this.iv = iv;
        this.context = context;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream bos = null;
        try {
            URL url = new URL("http://prw.kyodonews.jp/prwfile/release/M102245/201403149047/_prw_PI1fl_2o2KuN2D.jpg");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            file_length = httpURLConnection.getContentLength();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = httpURLConnection.getInputStream();
                bos = new ByteArrayOutputStream();
                byte[] buff =  new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    bos.write(buff, 0, len);
                    publishProgress(file_length,bos.size());
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(context);
        pd.setTitle("test");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        pd.setMax(100);
        pd.setProgress(0);
        pd.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        pd.setMax(values[0]);
        pd.setProgress(values[1]);
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        Bitmap bt = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        iv.setImageBitmap(bt);
        pd.dismiss();
    }
}



2016年11月4日金曜日

Android JSONObject 练习

Android JSONObject 练习

1.  JSON链接
     http://cdefgab.web.fc2.com/song.json


public class DownJson {

    public void ejson() {
        String data = jsonString();
        HashMap<String, String> hh = new HashMap<String, String>();
        HashMap<Integer, HashMap<String, String>> hl = new HashMap<Integer, HashMap<String, String>>();

        try {
            JSONObject js = new JSONObject(data);
            JSONObject js2 = js.getJSONObject("photos");
            hh.put("stat", js.getString("stat"));
            hh.put("page", js2.getString("page"));
            hh.put("pages", js2.getString("pages"));
            hh.put("perpage", js2.getString("perpage"));
            hh.put("total", js2.getString("total"));

            String ja = js2.getString("photo");
            JSONArray jaa = new JSONArray(ja);

            for (int i = 0; i < jaa.length(); i++) {
                JSONObject t1 = jaa.getJSONObject(i);
                HashMap<String, String> hmt = new HashMap<String, String>();
                hmt.put("id", t1.getString("id"));
                hmt.put("owner", t1.getString("owner"));
                hmt.put("secret", t1.getString("secret"));
                hmt.put("server", t1.getString("server"));
                hmt.put("farm", t1.getString("farm"));
                hmt.put("title", t1.getString("title"));
                hmt.put("ispublic", t1.getString("ispublic"));
                hmt.put("isfriend", t1.getString("isfriend"));
                hmt.put("isfamily", t1.getString("isfamily"));
                hl.put(i, hmt);
            }

            System.out.println("-----------------------");
            System.out.println(hl.get(0).get("title"));
            System.out.println("-----------------------");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public static String jsonString() {
        String jstring = null;
        InputStream is = null;
        try {
            URL u = new URL("http://cdefgab.web.fc2.com/song.json");
            HttpURLConnection h = (HttpURLConnection) u.openConnection();
            h.setRequestMethod("GET");
            h.setDoInput(true);
            h.setConnectTimeout(3000);
            h.setReadTimeout(3000);
            if (h.getResponseCode() == 200) {
                byte[] buff = new byte[1024];
                int len = 0;
                is = h.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                jstring = baos.toString("utf-8");
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jstring;
    }
}


2016年11月2日水曜日

ByteArrayOutputStream 练习

ByteArrayOutputStream 练习


import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip
    // http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip
    // http://cdefgab.web.fc2.com/song.json

    httpd h = new httpd("http://cdefgab.web.fc2.com/song.json");
    h.std();
    }
}

class httpd{
    private String durl;
 
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
     
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            bao.write(buff,0,len);
            System.out.println(len);
        }
     
        fis.close();
        System.out.println(bao.toString());
        }catch(Exception e){
         
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}

2016年11月1日火曜日

HttpFileDownload 练习

HttpFileDownload 练习

https://paiza.io/projects/6lTQWbqAzvT-IEAHaRl4AA



import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws Exception {

    // https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be
    // https://images-na.ssl-images-amazon.com/images/I/81M-I12yh7L._SL1500_.jpg
    // http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip

    httpd h = new httpd("https://www.youtube.com/watch?v=fRh_vgS2dFE&feature=youtu.be");
    h.std();
    }
}

class httpd{
    private String durl;
   
    public httpd(String durl){
        this.durl = durl;
    }

    public void std(){
        System.out.println("sdt()-start");
        try{
        FileOutputStream fis = new FileOutputStream("demo.db");
        InputStream is = dis();
        byte[] buff = new byte[10240];
        int len = 0;
       
        System.out.println("koko");
        while( (len = is.read(buff)) != -1){
            fis.write(buff,0,len);
            fis.flush();
            System.out.println(len);
        }
       
        fis.close();
        }catch(Exception e){
           
        }finally{
            File f = new File("demo.db");
            System.out.println(f.getName());
            System.out.println(f.getAbsolutePath());
        }
    }

    public InputStream dis(){
        InputStream inputStream = null;
        try{
            URL url = new URL(durl);
            System.out.println("url = " + durl);
            HttpURLConnection httpurl = (HttpURLConnection)url.openConnection();
            httpurl.setConnectTimeout(3000);
            httpurl.setDoInput(true);
            httpurl.setReadTimeout(3000);
            httpurl.setRequestMethod("GET");
            if(httpurl.getResponseCode() == 200){
                System.out.println("paus" + httpurl.getResponseCode());
                inputStream = httpurl.getInputStream();
            }
        }catch(Exception e){
        }
        return inputStream;
    }
}

HttpFileDownload 练习

练习

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Http {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                // HttpDown hd = new
                // HttpDown("http://gdl.square-enix.com/ffxiv/inst/ffxiv-heavensward-bench.zip");
                HttpDown hd = new HttpDown("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");

                hd.SavetoDisk();
        }
}

class HttpDown {
        private String URL_PATH;

        public HttpDown(String URL_PATH) {
                this.URL_PATH = URL_PATH;
        }

        public void SavetoDisk() {
                InputStream is = null;
                FileOutputStream fo = null;
                try {
                        fo = new FileOutputStream("e:\\testFile.zip");
                        is = DownStream();
                        byte[] buffer = new byte[1024 * 1024];
                        int len = 0;
                        while ((len = is.read(buffer)) != -1) {
                                fo.write(buffer, 0, len);
                                fo.flush();
                                System.out.println(len);
                        }

                } catch (Exception e) {
                        e.printStackTrace();
                } finally {
                        try {
                                if (fo != null) {
                                        fo.close();
                                }
                                if (is != null) {
                                        is.close();
                                }
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }

        }

        public InputStream DownStream() {
                InputStream inputStream = null;
                HttpURLConnection hul = null;

                try {
                        URL rul = new URL(URL_PATH);
                        hul = (HttpURLConnection) rul.openConnection();
                        hul.setConnectTimeout(3000);
                        hul.setReadTimeout(3000);
                        hul.setDoInput(true);
                        hul.setRequestMethod("GET");
                        if (hul.getResponseCode() == 200) {
                                inputStream = hul.getInputStream();
                        } else {
                                inputStream = null;
                        }

                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {

                }
                return inputStream;
        }

}

java HTTP 协议下的文件下载

java HTTP 协议下的文件下载

1. 建立HTTP的链接,返回输入流。
2. 读取输入流,写入输出流。


import java.net.*;
import java.io.*;
class demo{
public static void main(String[] args) {
HttpUtils hu = new HttpUtils("http://bizingeinoutetyou.com/bizinkisya/wp-content/uploads/2015/04/kiritanimirei_i04.jpg");
hu.saveImageToDisk();
}
}

class HttpUtils{
// private static String url_path = "http://bizingeinoutetyou.com/bizinkisya/wp-content/uploads/2015/04/kiritanimirei_i04.jpg";
private static String url_path ;
public HttpUtils(String url_path){
this.url_path = url_path;
}

public void saveImageToDisk(){
InputStream inputstream = getInputStream();
FileOutputStream fileoutputstream = null;
byte[] buff = new byte[1024];
int len = 0;
try{
fileoutputstream = new FileOutputStream("test.jpg");
while((len = inputstream.read(buff)) != -1){
fileoutputstream.write(buff,0,len);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(inputstream != null){
try{
inputstream.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(fileoutputstream != null){
try{
fileoutputstream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}


public static InputStream getInputStream(){
InputStream inputstream = null;
HttpURLConnection httpurlconnection = null;
try{
URL url = new URL(url_path);
httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setConnectTimeout(3000);
httpurlconnection.setDoInput(true);
httpurlconnection.setRequestMethod("GET");
int responseCode = httpurlconnection.getResponseCode();
if(responseCode == 200){
inputstream = httpurlconnection.getInputStream();
}
System.out.println(url.getFile());
System.out.println(httpurlconnection.getResponseCode());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return inputstream;
}
}

2016年10月31日月曜日

Android FileWriter,FileReader

Android FileWriter,FileReader

文件的保存位置有要求
   String path ="/data/data/" + this.getPackageName() +"/demo.txt";



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Test();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void Test() throws IOException {
        final String tag = "testFile";
        String path ="/data/data/" + this.getPackageName() +"/demo.txt";
        FileWriter fileWriter = new FileWriter(path);

        for( int i = 0; i <102; i++){
            fileWriter.write(String.valueOf(i));
        }
        fileWriter.flush();
        fileWriter.close();

        FileReader fileReader = new FileReader(path);
        char[] buf = new char[24];
        int num;
        while(((num = fileReader.read(buf)) != 0)){
            System.out.println("---" + new String(buf,0,num));
        }
        fileReader.close();
    }
}


结果
com.example.java.m1031a I/System.out: ---012345678910111213141516
com.example.java.m1031a I/System.out: ---171819202122232425262728
com.example.java.m1031a I/System.out: ---293031323334353637383940
com.example.java.m1031a I/System.out: ---414243444546474849505152
com.example.java.m1031a I/System.out: ---535455565758596061626364
com.example.java.m1031a I/System.out: ---656667686970717273747576
com.example.java.m1031a I/System.out: ---777879808182838485868788
com.example.java.m1031a I/System.out: ---899091929394959697989910
com.example.java.m1031a I/System.out: ---0101