关闭

第一行代码Android学习(十一)

标签: androidhttp协议webviewLocationMa数据
472人阅读 评论(0) 收藏 举报
分类:

第一行代码Android学习:第十一部分主要涉及到WebView、Http协议访问网络、解析JSON格式数据、LocationManager的基本用法
1.DYHDM_10_00NetworkTest

  • AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
  • activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/wv"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/bt_send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/tv_response"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>
  • 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<Map<String, String>> lists = gson.fromJson(response,
                new TypeToken<List<Map<String, String>>>() {
                }.getType());
        for (Map<String, String> 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<NameValuePair> params = new ArrayList<NameValuePair>();
                    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
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  • activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/position_test_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>
  • 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<String> 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);
        }
    }
}

代码下载地址

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13508次
    • 积分:608
    • 等级:
    • 排名:千里之外
    • 原创:49篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类