2012-08-13 141 views
1

每次用戶打開應用程序時,我們都會檢查我們是否獲得了當前位置。如果沒有,該應用程序會要求他在LocationManager中啓用位置,然後再回到應用程序。問題:有時,在某些手機中,即使在啓用位置並且用戶回到應用後,位置仍然是null。所以用戶被困在一個循環中。爲什麼位置仍然爲空?我能做什麼?啓動應用程序時獲取當前位置

String locationContext = Context.LOCATION_SERVICE; 

locationManager = (LocationManager) getSystemService(locationContext); 
Location location = locationManager.getLastKnownLocation(locationProvider); 

if (location != null) { 
    double latitude = location.getLatitude(); 
    double longitude = location.getLongitude(); 

    final String lat = String.valueOf(latitude); 
    final String lon = String.valueOf(longitude); 

    System.out.println("Localisation: " + lat + " " + lon); 

    SharedPreferences preferences = PreferenceManager 
     .getDefaultSharedPreferences(getBaseContext()); 
    String id = preferences.getString("id", null); 
    new sendLocation().execute(id, lat, lon); 
} else { 
    System.out.println("NO LOCATION!!"); 
    AlertDialog.Builder alert = new AlertDialog.Builder(Home.this); 

    alert.setTitle("Get started"); 
    alert.setMessage("We need your location to detect places nearby. Please enable -Wireless Networks- in your location settings to get started."); 

    // Set an EditText view to get user input 
    final TextView input = new TextView(Home.this); 
    alert.setView(input); 

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 

    public void onClick(DialogInterface dialog, int whichButton) { 

     startActivity(new Intent(
      android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 

    } 
    }); 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

    public void onClick(DialogInterface dialog, int whichButton) { 
     // Canceled. 
    } 
    }); 

    alert.show(); 
} 
+0

您是否可以在xml中啓用位置服務的許可 – Riskhan 2012-08-13 12:18:33

+0

我已經啓用了權限。正如我解釋的那樣,獲取位置信息並非總是如此 – user420574 2012-08-13 14:11:39

回答

0

當用戶在手機中啓用位置功能時,Android設備不一定會自動刷新位置信息。

爲了確保您獲得某種位置,您需要註冊一個LocationListener以進行單個或多個更新。

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0.0f, this); 

而在你的主類是「本」,添加implements LocationListener,並添加下面的方法:

public void onLocationChanged(Location location) { 
    //This "location" object is what will contain updated location data 
    //when the listener fires with a location update 
} 

public void onStatusChanged(String provider, int status, Bundle extras) { 
    //Required by LocationListener - you can do nothing here 
} 

public void onProviderEnabled(String provider) { 
    //Required by LocationListener - you can do nothing here 
} 

public void onProviderDisabled(String provider) { 
    //Required by LocationListener - you can do nothing here 
} 

當你得到一個位置更新,您可以通過禁用監聽器:在LocationListener的

locationManager.removeUpdates(this); 

更多的文檔在這裏: http://developer.android.com/reference/android/location/LocationListener.html

+0

我正在嘗試你的方法,但有一些問題。請看看:http://stackoverflow.com/q/41206885/6144372 – 2016-12-18 09:35:37

相關問題