android开发:location包实现定位的功能

申明:不要使用23以上的API,因为多了一个权限审核,会抛出异常,我今天就是因为Android Studio自动设置成23的API了,导致异常。

开发定位的功能很简单,首先获取LocationManager服务对象:

LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);

然后使用LocationManager对象的getLastKnownLocation方法返回一个Location对象,Location包含了经度、维度、海拔、速度等等信息,对,这就是我们要的。
代码:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
StringBuffer sb = new StringBuffer();
if(location!=null) {
 sb.append("经度:" + location.getLatitude() + " ");
 sb.append("纬度:" + location.getLongitude() + " ");
 sb.append("速度:" + location.getSpeed() + " ");
 sb.append("提供者:" + location.getProvider() + " ");
 sb.append("精准度:" + location.getAccuracy() + " ");
 sb.append("海拔:" + location.getAltitude() + " ");
 sb.append("getBearing:" + location.getBearing() + " ");
 sb.append("getElapsedRealtimeNanos:" + location.getElapsedRealtimeNanos() + " ");
}

text.setText( sb);

如果我们需要在特定的时间内更新GPS位置,那么我们需要创建监听器LocationListener,LocationListener可以为我们更新位置信息,使用LocationManager方法:

public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListenerlistener)

Added in API level 1

Register for location updates using the named provider, and a pending intent.

See requestLocationUpdates(long, float, Criteria, PendingIntent) for more detail on how to use this method.

Parameters
provider the name of the provider with which to register
minTime minimum time interval between location updates, in milliseconds
minDistance minimum distance between location updates, in meters
listener a LocationListener whose onLocationChanged(Location) method will be called for each location update

监听器的代码:

new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        double lnt = location.getLatitude() ;
        double log = location.getLongitude() ;

        //toast("onLocationChanged:lnt[" + lnt + "] log[" + log + "]");
        StringBuffer sb = new StringBuffer();

        sb.append("经度:" + location.getLatitude() + " ");
        sb.append("纬度:" + location.getLongitude() + " ");
        sb.append("速度:" + location.getSpeed() + " ");
        sb.append("提供者:" + location.getProvider() + " ");
        sb.append("精准度:" + location.getAccuracy() + " ");
        sb.append("海拔:" + location.getAltitude() + " ");
        sb.append("getBearing:" + location.getBearing() + " ");
        sb.append("getElapsedRealtimeNanos:" + location.getElapsedRealtimeNanos() + " ");
        text.setText(sb.toString());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        toast("onStatusChanged");
    }

    @Override
    public void onProviderEnabled(String provider) {
        toast("onProviderEnabled");
    }

    @Override
    public void onProviderDisabled(String provider) {
        toast("onProviderDisabled");
    }
};

全部代码:

package com.lanxin.testlocation2;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "LocatinLog";
    TextView text;
    Context mContext;
    LocationManager lm;
    Geocoder geocoder;
    LocationListener ll;
    LocationProvider lp;
    Location location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        findid();
        init();

    }


    private void init() {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        geocoder = new Geocoder(mContext);
        location = new Location(LocationManager.GPS_PROVIDER);

        ll = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                double lnt = location.getLatitude() ;
                double log = location.getLongitude() ;

                //toast("onLocationChanged:lnt[" + lnt + "] log[" + log + "]");
                StringBuffer sb = new StringBuffer();

                sb.append("经度:" + location.getLatitude() + " ");
                sb.append("纬度:" + location.getLongitude() + " ");
                sb.append("速度:" + location.getSpeed() + " ");
                sb.append("提供者:" + location.getProvider() + " ");
                sb.append("精准度:" + location.getAccuracy() + " ");
                sb.append("海拔:" + location.getAltitude() + " ");
                sb.append("getBearing:" + location.getBearing() + " ");
                sb.append("getElapsedRealtimeNanos:" + location.getElapsedRealtimeNanos() + " ");
                text.setText(sb.toString());
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                toast("onStatusChanged");
            }

            @Override
            public void onProviderEnabled(String provider) {
                toast("onProviderEnabled");
            }

            @Override
            public void onProviderDisabled(String provider) {
                toast("onProviderDisabled");
            }
        };



        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        StringBuffer sb = new StringBuffer();
        if(location!=null) {
            sb.append("经度:" + location.getLatitude() + " ");
            sb.append("纬度:" + location.getLongitude() + " ");
            sb.append("速度:" + location.getSpeed() + " ");
            sb.append("提供者:" + location.getProvider() + " ");
            sb.append("精准度:" + location.getAccuracy() + " ");
            sb.append("海拔:" + location.getAltitude() + " ");
            sb.append("getBearing:" + location.getBearing() + " ");
            sb.append("getElapsedRealtimeNanos:" + location.getElapsedRealtimeNanos() + " ");
        }



        text.setText( sb);


    }

    private void findid() {
        mContext = this;
        text = (TextView) findViewById(R.id.text);
        Button go = (Button)findViewById(R.id.go);
        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                toast("onLocationChanged:lnt[" + location.getLatitude() + "] log[" + location.getLongitude()  + "]");
                try {
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);

                    if(addresses!=null && addresses.size() > 0){
                        StringBuffer sb = new StringBuffer();

                        for(int i=0;i<addresses.size();i++){
                            Address adr = addresses.get(i);
                            sb.append("lat"+i+":"+adr.getLatitude()+"lnt"+i+":"+adr.getLongitude()+"  \n\t ");
                        }
                        text.setText(sb.toString());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void toast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(ll);//程序注销时应该移除监听器,以减少电量的使用

    }

    protected void onResume() {
        super.onResume();

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);//程序恢复的时候我们注册监听器
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 Comment

  1. Alan Author 六月 21, 2016 (10:32 下午)

    源码下载:http://pan.baidu.com/s/1mipQjJ6

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |