位置服务

来源:互联网 发布:软件开发包 编辑:程序博客网 时间:2024/04/30 08:42
1package com.example.locationtest;    import java.util.List;    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 org.apache.http.util.EntityUtils;  import org.json.JSONArray;  import org.json.JSONObject;    import android.location.Location;  import android.location.LocationListener;  import android.location.LocationManager;  import android.os.Bundle;  import android.os.Handler;  import android.os.Message;  import android.app.Activity;  import android.content.Context;  import android.view.Menu;  import android.widget.TextView;  import android.widget.Toast;    public class MainActivity extends Activity  {      private TextView positionTextView;      private LocationManager locationManager;      private String provider;      public static final int SHOW_LOCATION=0;        protected void onCreate(Bundle savedInstanceState)      {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          positionTextView = (TextView) findViewById(R.id.position_text_view);          locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          List<String> providerList = locationManager.getProviders(true);          if (providerList.contains(LocationManager.GPS_PROVIDER))          {              provider = LocationManager.GPS_PROVIDER;            } else if (providerList.contains(LocationManager.NETWORK_PROVIDER))          {              provider = LocationManager.NETWORK_PROVIDER;          } else          {              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);      }        protected void onDestory()      {          super.onDestroy();          if (locationManager!=null)          {              locationManager.removeUpdates(locationListener);          }      }        LocationListener locationListener = new LocationListener()      {          public void onStatusChanged(String provider, int status, Bundle extras)          {          }            public void onProviderEnabled(String provider)          {          }          public void onProviderDisabled(String provider)          {            }              public void onLocationChanged(Location location)          {              showLocation(location);          }                            };        private void showLocation(final Location location)      {          /*String currentPosition = "latitude is" + location.getLatitude() + "\n"                  + "longitude is" + location.getLongitude();          positionTextView.setText(currentPosition);      }  }*/          new Thread(new Runnable(){              public void run(){                  try{                  StringBuilder url=new StringBuilder();                  url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");                  url.append(location.getLatitude()).append(",");                  url.append(location.getLongitude());                  url.append("&sensor=false");                  HttpClient httpClient = new DefaultHttpClient();                  HttpGet httpGet = new HttpGet(url.toString());                  // 在请求消息头中指定语言,保证服务器会返回中文数据                  httpGet.addHeader("Accept-Language", "zh-CN");                  HttpResponse httpResponse = httpClient.execute(httpGet);                  if (httpResponse.getStatusLine().getStatusCode() == 200) {                      HttpEntity entity = httpResponse.getEntity();                      String response = EntityUtils.toString(entity, "utf-8");                      JSONObject jsonObject = new JSONObject(response);                      // 获取results节点下的位置信息                      JSONArray resultArray = jsonObject.getJSONArray ("results");                      if (resultArray.length() > 0) {                          JSONObject subObject = resultArray. getJSONObject(0);                          String address = subObject.getString ("formatted_address");                          Message message = new Message();                          message.what = SHOW_LOCATION;                          message.obj = address;                          handler.sendMessage(message);                      }                  }                    }catch(Exception e){                      e.printStackTrace();                  }              }          }).start();        }      private Handler handler = new Handler() {          public void handleMessage(Message msg) {              switch (msg.what) {              case SHOW_LOCATION:                  String currentPosition = (String) msg.obj;                  positionTextView.setText(currentPosition);                  break;              default:                  break;              }          }      };      }  2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"            android:layout_width="match_parent"      android:layout_height="match_parent"      >      <TextView           android:id="@+id/position_text_view"          android:layout_width="wrap_content"          android:layout_height="wrap_content"/>            </LinearLayout>3<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.locationtest"    android:versionCode="1"    android:versionName="1.0" >     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.INTERNET" />    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.locationtest.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

0 0
原创粉丝点击