基于位置的服务

一、运行效果图

二、核心代码

MainActivity.java

package 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;
			}
		}
	};


}


 

activity_main.xml

<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>


 

增加权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>


三、运行中出现的问题

代码运行并没有报错,一开始出现定位不到位置,整个界面全是空白,更改以后又出现定位不正确的问题,如图二所示,问题还没有解决,希望老师指正!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值