欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android的用户定位---location使用 博客分类: android androidloationManagergps 

程序员文章站 2024-03-14 22:26:53
...

四个步骤:

1.添加权限

2.获取locationManager对象

3.获取locationProvider

4.绑定locationListener对象

 

 

首先在Manifest.xml中添加权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> //此为高精度--GPS定位选择

 

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>//此为精度一般--NetWork 定位可选上下2个

 

代码:

package com.example.location1;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Loaction extends Activity {
	
	EditText et1;
	EditText et2;
	Button bt;
	LocationManager lm;
	LocationListener listener;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        bt = (Button) findViewById(R.id.bt);
        bt.setText("绑定监听器");
        bt.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
		      //获得最适合的provider	  
		        Criteria cr = new Criteria();
		        //设置经度 
		        cr.setAccuracy(Criteria.ACCURACY_FINE);
		        //是否需要提供海拔信息
		        cr.setAltitudeRequired(false);
		        //设置需要方向信息
		        cr.setBearingRequired(false);
		        //设置是否产生费用
		        cr.setCostAllowed(false);
		        //设置电量高低
		        cr.setPowerRequirement(Criteria.POWER_LOW);
		        //设置速度经度
		        cr.setSpeedRequired(false);	
				
			lm = (LocationManager) Loaction.this.getSystemService(Context.LOCATION_SERVICE);
			//true 只在打开的provider中寻找 false 在所有的provider中寻找最合适的
			String provider = lm.getBestProvider(cr, false);
			System.out.println(provider);//---GPS 最合适的
			lm.requestLocationUpdates(provider, 0, 0, listener);
			}
		});
      
        listener = new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onLocationChanged(Location location) {
				double lg = location.getLongitude();
				double la = location.getLatitude();
				et1.setText(lg+"");
				et2.setText(la+"");
			}
		};
    }
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}