2017-09-06 50 views
1

我想要做的是從用戶獲取位置。首先它嘗試通過GPS獲取位置並檢查位置是否可用。如果不是那麼它它試圖通過網絡塔。當GPS打開時,它工作正常。但是,當我關閉GPS它不使用越來越位置的網絡供應商試圖獲取與細胞塔位置,但仍然返回空

manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    provider = manager.getBestProvider(new Criteria(), false); 

    Log.i("ITEMSET best", provider); 


    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 

    Log.i("ITEMSET provider", provider); 

    location = manager.getLastKnownLocation(provider); 
    Log.i("ITEMSET netLoc", location + ""); 
    if(location==null) { 
     provider = LocationManager.NETWORK_PROVIDER; 
     location = manager.getLastKnownLocation(provider); 
     Log.i("ITEMSET netLoc", location + "qqq"); 
    } 



    Log.i("ITEMSET current", provider); 
    Log.i("ITEMSET location", location + ""); 

Logcat

地點最初是空,因爲GPS是沒有開啓。但隨後將提供商更改爲網絡提供商。但是仍然位置空

+0

你有沒有給予好的位置權限? –

+0

是的,我已經給出了很好的位置和粗略的位置權限。 –

+0

可能你沒有請求位置更新,這就是爲什麼它給出問題 –

回答

1

檢查是否網絡啓用與否

isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

則:

 if (isNetworkEnabled) { 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,10, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 

         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 


        } 
       } 
+0

就是這樣。看起來像提供商沒有啓用 –

0

您應該使用GoogleApiClient讓你的位置。請訪問this post