Android獲取位置信息

1.AndroidMainfext.xml添加權(quán)限

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

2.AndroidMainfext.xml 加入android:targetSdkVersion="23" (為什么要加入這個(gè)是為了配合安卓6.0以上系統(tǒng)需要?jiǎng)討B(tài)申請(qǐng)權(quán)限,加入這個(gè)不寫或者低于23則23以及以上的會(huì)無法獲得權(quán)限)
3.獲取定位服務(wù)以及當(dāng)前可用的控制器

private static LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if(location != null){
                String string = "緯度為:" + location.getLatitude() + ",經(jīng)度為:"+ location.getLongitude();
                Log.i(logTag,"string"+string);
                AndroidLocation.getAddress(location);
                AndroidLocation.onActivityStoped();
            }
        }
 
        @Override
        public void onProviderDisabled(String arg0) {
        }
 
        @Override
        public void onProviderEnabled(String arg0) {
        }
 
        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }
    };
 public static void startLocation(Context context){
        mContext = context;
        //獲取定位服務(wù)
        m_locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //獲取當(dāng)前可用的位置控制器
        List<String> list = m_locationManager.getProviders(true);
        if (list.contains(LocationManager.GPS_PROVIDER)) {
            //是否為GPS位置控制器
            m_provider = LocationManager.NETWORK_PROVIDER;//NETWORK_PROVIDER GPS_PROVIDER
            Log.i(logTag,"is GPS");
        } 
        else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
        //是否為網(wǎng)絡(luò)位置控制器
            m_provider = LocationManager.NETWORK_PROVIDER;
            Log.i(logTag,"is network");
        }
        if(m_provider != null){
            Location location = m_locationManager.getLastKnownLocation(m_provider);
            if(location!=null){
                //AndroidLocation.getAddress(location);
//直接獲取
            }else{
//沒有需要加監(jiān)聽等待獲取
                m_locationManager.requestLocationUpdates(m_provider, 3000, 1, locationListener); 
            }
        }
    }

4.在activity的生命周期內(nèi)要記得刪除listener,我的需求是獲取到地址就可以了不需要監(jiān)聽位置的變化所以獲取到了直接就remove掉了

public static void onActivityStoped(){
        if(locationListener != null){
            m_locationManager.removeUpdates(locationListener);   
            locationListener = null;
        }
        Log.i(logTag,"onActivityStoped");
    }

5.以上獲得的是經(jīng)緯度,這個(gè)還需要一次轉(zhuǎn)化,轉(zhuǎn)化為我們熟悉的XX省XX市XX街道這種

 private static String getAddress(Location location){
        //用來接收位置的詳細(xì)信息
        List<Address> result = null;
        String addressLine = "";
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(mContext, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(result != null && result.get(0) != null){
                //這塊獲取到的是個(gè)數(shù)組我們?nèi)∫粋€(gè)就好 下面是具體的方法查查API就能知道自己要什么
                //result.get(0).getCountryName()
            
            Log.i("address",addressLine);
            //Toast.makeText(mContext,result.get(0).toString(),Toast.LENGTH_LONG).show();
        }
        
        return addressLine;
    }

6.做到這里完成了一大半了 試著去獲取下也有了,但是但是但是重要的事情說三遍安卓6.0以上的系統(tǒng)獲取不到(悲傷地表情,查了好多地方也就介紹到這里了)我們繼續(xù)
我們要做的是前面說的動(dòng)態(tài)加載權(quán)限代碼如下:

public static void initPermission(Context context) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //請(qǐng)求權(quán)限
                ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION);
            }else{
                startLocation(context);
            }
        }else{
            startLocation(context);
        }
    }

但是加上這個(gè)就好了嗎?顯然并不是實(shí)際上加上這個(gè)病不起什么作用;關(guān)鍵在如下:
一定要實(shí)現(xiàn)OnRequestPermissionsResultCallback 在權(quán)限結(jié)果有了之后再初始化定位(AndroidLocation.REQUEST_CODE_LOCATION 是requestPermissions申請(qǐng)權(quán)限的一個(gè)自己定義的變量隨便寫)

import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback;
public class MainActivity extends Activity implements OnRequestPermissionsResultCallback{
...
@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        if(grantResults.length == 0){
            return;
        }
        Log.i("AndroidLocation.REQUEST_CODE_LOCATION",AndroidLocation.REQUEST_CODE_LOCATION+"==="+requestCode);
        switch (requestCode) {
        case AndroidLocation.REQUEST_CODE_LOCATION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//              Toast.makeText(MainActivity.this, "授權(quán)位置信息 Denied", Toast.LENGTH_SHORT)
//                .show();
                location.init(this);
            }
            
            break;
        default:
            //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
...
}

原理很簡(jiǎn)單,做個(gè)備忘!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android系統(tǒng)權(quán)限 Android 是一個(gè)權(quán)限分隔的操作系統(tǒng),其中每個(gè)應(yīng)用都有其獨(dú)特的系統(tǒng)標(biāo)識(shí)(Linux 用...
    ZHLeo閱讀 7,572評(píng)論 3 16
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,045評(píng)論 25 709
  • Android M 對(duì)權(quán)限管理系統(tǒng)進(jìn)行了改版,之前我們的 App 需要權(quán)限,只需在 manifest 中申明即可,...
    Android輪子哥閱讀 13,993評(píng)論 6 54
  • 一道殘陽(yáng)鋪水中,半江瑟瑟半江紅。可憐九月初三夜,露似真珠月似弓。 一道殘陽(yáng)漸沉江中,半江碧綠半江艷紅。最可愛的詩(shī)那...
    何詩(shī)閱讀 656評(píng)論 0 0
  • 海棠社以“荊軻”為主題作業(yè) 荊軻拔劍青史駐,秦王一統(tǒng)負(fù)罵名。 從來帝王招恨意,是非何堪后人評(píng)。 倘使當(dāng)日真得手,安...
    云若V閱讀 278評(píng)論 8 3

友情鏈接更多精彩內(nèi)容