Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 第一行代碼Android學習(十一)

第一行代碼Android學習(十一)

編輯:關於Android編程

第一行代碼Android學習:第十部分主要涉及到WebView、Http協議訪問網絡、解析JSON格式數據、LocationManager的基本用法
1.DYHDM_10_00NetworkTest

AndroidManifest.xml
activity_main.xml


    
MainActivity.java
package com.example.dyhdm_10_00networktest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

    private WebView webView;
    public static final int SHOW_RESPONSE = 0;
    private Button sendResquest;
    private TextView responseText;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case SHOW_RESPONSE:
                String response = (String) msg.obj;
                responseText.setText(response);
                // parseJSONWithJSONObject(response);
                parseJSONWithGSON(response);
                break;

            default:
                break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*
         * webView = (WebView) findViewById(R.id.wv); // 讓WebView支持JavaScript腳本
         * webView.getSettings().setJavaScriptEnabled(true);
         * webView.setWebViewClient(new WebViewClient() { //
         * 當需要從一個網頁跳到另一個網頁,目標網頁仍在當前WebView中打開
         * 
         * @Override public boolean shouldOverrideUrlLoading(WebView view,
         * String url) { view.loadUrl(url); return true;//
         * 當前WebView可以處理打開新網頁的請求,不借助系統浏覽器 } });
         * webView.loadUrl("http://www.baidu.com");
         */
        sendResquest = (Button) findViewById(R.id.bt_send_request);
        responseText = (TextView) findViewById(R.id.tv_response);
        sendResquest.setOnClickListener(this);
    }

    /**
     * TODO 解析JSON數據,用GSON
     * 
     * @throw
     * @return void
     */
    protected void parseJSONWithGSON(String response) {
        Gson gson = new Gson();
        List> lists = gson.fromJson(response,
                new TypeToken>>() {
                }.getType());
        for (Map map : lists) {
            Log.i("zza", map.get("zw"));
        }
    }

    /**
     * TODO 解析JSON數據,用JSONObject
     * 
     * @throw
     * @return void
     */
    protected void parseJSONWithJSONObject(String response) {
        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Log.i("zza", jsonObject.get("patientId").toString());
                Log.i("zza", jsonObject.get("zw").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重載方法
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_send_request) {
            // sendRequestWithHttpURLConnection();
            sendRequestWithHttpClient();
        }
    }

    /**
     * TODO 使用HttpClient開啟線程發送網絡請求
     * 
     * @throw
     * @return void
     */
    private void sendRequestWithHttpClient() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    // 發送GET請求
                    // HttpGet httpGet = new HttpGet("http://www.baidu.com");
                    // 發送POST請求
                    HttpPost httpPost = new HttpPost(
                            "http://192.168.1.112:9000/newapk.Prescription/getPrescription");
                    List params = new ArrayList();
                    params.add(new BasicNameValuePair("patientId", "666666"));
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                            params, "UTF-8");
                    httpPost.setEntity(entity);
                    // HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        // 請求和響應都成功了
                        HttpEntity entity1 = httpResponse.getEntity();
                        String response = EntityUtils
                                .toString(entity1, "UTF-8");

                        Message message = new Message();
                        message.what = SHOW_RESPONSE;
                        // 將服務器返回的結果存放在Message中
                        message.obj = response.toString();
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * TODO 使用HttpURLConnection開啟線程發送網絡請求
     * 
     * @throw
     * @return void
     */
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    URL url = new URL("http://www.baidu.com");
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    /*
                     * 提交數據給服務器 conn.setRequestMethod("POST"); DataOutputStream
                     * out = new DataOutputStream(conn.getOutputStream());
                     * out.writeBytes("username=admin&password=123455");
                     */
                    InputStream in = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }

            }
        }).start();
    }

}

2.DYHDM_11_00LocationTest

AndroidManifest.xml
activity_main.xml


    

MainActivity.java
package com.example.dyhdm_11_00locationtest;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private TextView postionTextView;
    private LocationManager locationManager;
    private String provider;
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            showLocation(location);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        postionTextView = (TextView) findViewById(R.id.position_test_view);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 獲取所有可用的位置提供器
        List providderList = locationManager.getProviders(true);
        if (providderList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providderList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            // 當沒有可用的位置提供器時,彈出Toast提示用戶
            Toast.makeText(this, "No location provider to use",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            showLocation(location);
        }
        // 四個參數
        // 第一個:位置提供器的類型
        // 第二個:監聽位置變化的事件間隔
        // 第三個:移動距離
        // 第四個:監聽器
        locationManager.requestLocationUpdates(provider, 5000, 1,
                locationListener);
    }

    /**
     * TODO 顯示當前位置
     * 
     * @throw
     * @return void
     */
    private void showLocation(Location location) {
        String currentPosition = "latitude is " + location.getLatitude() + "\n"
                + "longitude is " + location.getLongitude();
        postionTextView.setText(currentPosition);
    }

    /**
     * 重載方法
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
            // 關閉程序時將監聽器移除
            locationManager.removeUpdates(locationListener);
        }
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved