2017年3月26日 星期日

Android在Thread中改變外部類別的View元件


  • 準備一個handler來接收呼叫,然後在handler中改變View元件:
Handler mHandler = new Handler() {
    @Override    public void handleMessage(Message msg) {
        if(msg.what == 1)
        {
            status.setText(response);
        }
        super.handleMessage(msg);
    }
};

  • Thread中要改變View元件處改為呼叫handler:

Message msg = mHandler.obtainMessage();
msg.what = 1;
msg.sendToTarget();

Android對URL的Get與Post


  • 首先,我們要注意的是:Android使用網路資源必須使用Thread!
     示範的Thread的寫法,是使用匿名內部類別+匿名物件的方式:

    (new Thread(){
        public void run() {
            //使用網路資源的程式寫在這裡!
        }
    }).start();
    
   因為使用了匿名類別,所以如果有建立變數,他的生存空間只在run裡面哦,但是run裡面可以存取外部類別的屬性!
  • POST的寫法:
        
         try {
            // Create a URL for the desired page        
            String response = "";
            URL url = new URL([要POST的網址]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(3000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            HashMap postDataParams = new HashMap();
            postDataParams.put("[參數名稱一]",[參數字串一]);
            postDataParams.put("[參數名稱二]",[]);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                 String line;
                 BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                 while ((line=br.readLine()) != null) {
                        response+=line;
                 }
             }
             else {
                 response="";
    
             }
         }
         catch (Exception e) {
                Log.d("Debug", e.toString());
         }
  • GET的寫法:

  • 跟POST一樣,只差在: 1.網址可以直接帶GET字串(?[參數名稱一]=[參數字串一]&[參數名稱二]=[參數字串二]) 2.conn.setRequestMethod("POST");改成conn.setRequestMethod("GET");