The Google Geocoding API provides a direct way to access a these services via an HTTP request.
So:通过输入所要查询的地名,来获取具体的相关信息。
一:直接使用new Thread(r).start(),然后在r的run()方法里面处理逻辑获取返回的json数据。(FC)
package cn.yh.googlemapwebservice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.yh.bean.Results;
import cn.yh.googlemapwebservice.R;
import com.google.gson.Gson;
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private String path;
private String jsonData = "";
private TextView resultTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.path);
button = (Button) findViewById(R.id.button);
resultTV = (TextView) findViewById(R.id.resultTV);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
path = "http://maps.googleapis.com/maps/api/geocode/json?address="
+ editText.getText().toString().trim()
+ "&sensor=false";
System.out.println(path);
Runnable r = new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient
.execute(new HttpGet(path));
HttpEntity entity = httpResponse.getEntity();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
jsonData += line;
}
System.out.println(jsonData);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
new Thread(r).start();
Gson gson = new Gson();
if (jsonData != null && jsonData != "") {
if (jsonData.endsWith("}")) {
Results results = gson
.fromJson(jsonData, Results.class);
System.out.println(results.toString());
resultTV.setText(results.toString());
button.setEnabled(true);
}
}
}
});
}
}
二:使用AsyncTask进行处理。一个AsyncTask仅执行一次,不能重复执行,快餐类的线程,一次用完。FC频发。
package cn.yh.googlemapwebservice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.yh.bean.Results;
import cn.yh.googlemapwebservice.R;
import com.google.gson.Gson;
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private String path;
private String jsonData = "";
private TextView resultTV;
private GetDataAsync getDataAsync;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.path);
button = (Button) findViewById(R.id.button);
resultTV = (TextView) findViewById(R.id.resultTV);
getDataAsync = new GetDataAsync();
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
path = "http://maps.googleapis.com/maps/api/geocode/json?address="
+ editText.getText().toString().trim()
+ "&sensor=false";
System.out.println(path);
getDataAsync.execute();
}
});
}
private class GetDataAsync extends AsyncTask<Void, Integer, String> {
@Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient
.execute(new HttpGet(path));
HttpEntity entity = httpResponse.getEntity();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
jsonData += line;
}
System.out.println(jsonData);
} catch (Exception e) {
System.out.println(e.toString());
}
return jsonData;
}
@Override
protected void onPostExecute(String result) {
Gson gson = new Gson();
if (jsonData != null && jsonData != "") {
if (result.endsWith("}")) {
Results results = gson.fromJson(result, Results.class);
System.out.println(results.toString());
resultTV.setText(results.toString());
button.setEnabled(true);
}
}
}
}
}
三:Handler。handler.post(r)这样并不会新起线程,只是执行的runnable里的run()方法,却没有执行start()方法,所以runnable走的还是MAIN线程。通过HandlerThread获取到looper却是可以新起线程,构建两个Handler,无参handler用来发送消息和处理消息,用开启新线程的handler来处理逻辑。(暂无FC)
package cn.yh.googlemapwebservice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.yh.bean.Results;
import cn.yh.googlemapwebservice.R;
import com.google.gson.Gson;
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private String path;
private String jsonData = "";
private TextView resultTV;
private Handler handler;
private Handler mainhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
jsonData = msg.getData().getString("jsonData");
Gson gson = new Gson();
if (jsonData != null && jsonData != "") {
if (jsonData.endsWith("}")) {
Results results = gson.fromJson(jsonData, Results.class);
System.out.println(results.toString());
resultTV.setText(results.toString());
button.setEnabled(true);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.path);
button = (Button) findViewById(R.id.button);
resultTV = (TextView) findViewById(R.id.resultTV);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
path = "http://maps.googleapis.com/maps/api/geocode/json?address="
+ editText.getText().toString().trim()
+ "&sensor=false";
System.out.println(path);
HandlerThread ht = new HandlerThread("handler thread");
ht.start();
handler = new Handler(ht.getLooper());
handler.post(thread);
}
});
}
Runnable thread = new Runnable() {
@Override
public void run() {
try {
jsonData = "";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient
.execute(new HttpGet(path));
HttpEntity entity = httpResponse.getEntity();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
jsonData += line;
}
System.out.println(jsonData);
} catch (Exception e) {
System.out.println(e.toString());
}
Message msg = mainhandler.obtainMessage();
msg.getData().putString("jsonData", jsonData);
mainhandler.sendMessage(msg);
}
};
}
实际上不需要开启新线程的Handler,只需要直接new Runnable()接口即可。
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/path"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:text="name" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET" />
<TextView
android:id="@+id/resultTV"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="查询结果:"/>
</LinearLayout>
加入:<uses-permission android:name="android.permission.INTERNET"/>权限,也是因为Internet访问不能再MAIN线程,所以需要开启新线程。
官方参考:https://developers.google.com/maps/documentation/geocoding/
其中Gson处理json数据:
返回json数据格式:
{
"results" : [
{
"address_components" : [
{
"long_name" : "纳斯",
"short_name" : "纳斯",
"types" : [ "locality", "political" ]
},
{
"long_name" : "基尔代尔郡",
"short_name" : "基尔代尔郡",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "基尔德尔",
"short_name" : "基尔德尔",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "爱尔兰",
"short_name" : "IE",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "爱尔兰共和国基尔德尔纳斯",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 53.2416,
"lng" : -6.62979
},
"southwest" : {
"lat" : 53.19867,
"lng" : -6.68849
}
},
"location" : {
"lat" : 53.2205654,
"lng" : -6.6593079
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 53.2416,
"lng" : -6.62979
},
"southwest" : {
"lat" : 53.19867,
"lng" : -6.68849
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
对应xml数据分析:
http://maps.googleapis.com/maps/api/geocode/xml?address=nao&sensor=false
Gson解析json对应简单javaBean:
package cn.yh.bean;
import java.util.List;
public class Results {
private String status;
private List<Result> results;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
@Override
public String toString() {
String Sresults = "";
for(Result r : results){
Sresults += r.toString();
}
return "Results [status=" + status + ", results=" + Sresults + "]";
}
}
package cn.yh.bean;
import java.util.Arrays;
public class Result {
private String[] types;
private String formatted_address;
public String[] getTypes() {
return types;
}
public void setTypes(String[] types) {
this.types = types;
}
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
@Override
public String toString() {
return "Result [types=" + Arrays.toString(types)
+ ", formatted_address=" + formatted_address + "]";
}
}