2016-01-02 42 views
2

當gps被禁用時,您可以用Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);啓用它,但是當我回到活動時,我沒有得到任何結果。我必須重新開始活動,換句話說,我必須回到之前的活動,然後重新打開它。你可以幫我嗎?經緯度未檢索

這是我doInBackground方法:

@Override 
protected String doInBackground(String... uri){ 

    final GPSTracker gpsTracker = new GPSTracker(myactivity); 
    final String[] latitudine = {null}; 
    final String[] longitudine = {null}; 

    if(gpsTracker.canGetLocation()) 
    { 
     latitudine[0] = String.valueOf(gpsTracker.latitude); 
     longitudine[0] = String.valueOf(gpsTracker.longitude); 
    } 
    else 
    { 
     myactivity.runOnUiThread(new Runnable() { 
      public void run() { 

       final Dialog dialog = new Dialog(myactivity); 
       dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
       dialog.setContentView(R.layout.position_alert_dialog); 

       Button dialogButton_deny = (Button) dialog.findViewById(R.id.deny); 
       Button dialogButton_allow = (Button) dialog.findViewById(R.id.allow); 

       dialogButton_allow.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         myactivity.startActivity(intent); 
         dialog.dismiss(); 

         if(gpsTracker.canGetLocation()) 
         { 
          latitudine[0] = String.valueOf(gpsTracker.latitude); 
          longitudine[0] = String.valueOf(gpsTracker.longitude); 

         }else{ 

          latitudine[0] = "34.0522300"; 
          longitudine[0] = "-118.2436800"; 

         } 

        } 
       }); 

       dialogButton_deny.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         dialog.dismiss(); 
        } 
       }); 

       dialog.show(); 

      } 
     }); 
    } 

GPSTracker

public class GPSTracker extends Service implements LocationListener { 
    private final Context mContext; 

    boolean isGPSEnabled = false; 

    boolean isNetworkEnabled = false; 

    boolean canGetLocation = false; 

    Location location; 
    double latitude; 
    double longitude; 

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters 

    private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute 

    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

      isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
      } else { 
       this.canGetLocation = true; 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()); 

        Log.d("Network", "Network"); 

        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         updateGPSCoordinates(); 
        } 
       } 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

         Log.d("GPS Enabled", "GPS Enabled"); 

         if (locationManager != null) { 
          location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          updateGPSCoordinates(); 
         } 
        } 
       } 
      } 
     } catch (Exception e) { 
      //e.printStackTrace(); 
      Log.e("Error : Location", "Impossible to connect to LocationManager", e); 
     } 

     return location; 
    } 

    public void updateGPSCoordinates() { 
     if (location != null) { 
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 
     } 
    } 

    public void stopUsingGPS() { 
     if (locationManager != null) { 
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
       if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        // TODO: Consider calling 
        // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
        // 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 Activity#requestPermissions for more details. 
        return; 
       } 
      } 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    public double getLatitude() 
    { 
     if (location != null) 
     { 
      latitude = location.getLatitude(); 
     } 

     return latitude; 
    } 

    public double getLongitude() 
    { 
     if (location != null) 
     { 
      longitude = location.getLongitude(); 
     } 

     return longitude; 
    } 

    public boolean canGetLocation() 
    { 
     return this.canGetLocation; 
    } 

    public List<Address> getGeocoderAddress(Context context) 
    { 
     if (location != null) 
     { 
      Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
      try 
      { 
       return geocoder.getFromLocation(latitude, longitude, 1); 
      } 
      catch (IOException e) 
      { 
       //e.printStackTrace(); 
       Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e); 
      } 
     } 

     return null; 
    } 

    public String getAddressLine(Context context) 
    { 
     List<Address> addresses = getGeocoderAddress(context); 
     if (addresses != null && addresses.size() > 0) 
     { 
      Address address = addresses.get(0); 

      return address.getAddressLine(0); 
     } 
     else 
     { 
      return null; 
     } 
    } 

    public String getLocality(Context context) 
    { 
     List<Address> addresses = getGeocoderAddress(context); 
     if (addresses != null && addresses.size() > 0) 
     { 
      Address address = addresses.get(0); 

      return address.getLocality(); 
     } 
     else 
     { 
      return null; 
     } 
    } 

    public String getSubLocality(Context context) 
    { 
     List<Address> addresses = getGeocoderAddress(context); 
     if (addresses != null && addresses.size() > 0) 
     { 
      Address address = addresses.get(0); 

      return address.getSubLocality(); 
     } 
     else 
     { 
      return null; 
     } 
    } 

    public String getPostalCode(Context context) 
    { 
     List<Address> addresses = getGeocoderAddress(context); 
     if (addresses != null && addresses.size() > 0) 
     { 
      Address address = addresses.get(0); 

      return address.getPostalCode(); 
     } 
     else 
     { 
      return null; 
     } 
    } 

    public String getCountryName(Context context) 
    { 
     List<Address> addresses = getGeocoderAddress(context); 
     if (addresses != null && addresses.size() > 0) 
     { 
      Address address = addresses.get(0); 

      return address.getCountryName(); 
     } 
     else 
     { 
      return null; 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) 
    { 
    } 

    @Override 
    public void onProviderDisabled(String provider) 
    { 
    } 

    @Override 
    public void onProviderEnabled(String provider) 
    { 
    }  

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

    @Override 
    public IBinder onBind(Intent intent) 
    { 
     return null; 
    } 
} 

編輯

public class GPSTracker extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks { 
private final Context mContext; 

boolean isPlayServicesEnabled = false; 

boolean isGPSEnabled = false; 

boolean isNetworkEnabled = false; 

boolean canGetLocation = false; 

Location location; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters 

private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute 

protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
     } else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()); 

       Log.d("Network", "Network"); 

       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        updateGPSCoordinates(); 
       } 
      } 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

        Log.d("GPS Enabled", "GPS Enabled"); 

        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         updateGPSCoordinates(); 
        } 
       } 
      } 
     } 
    } catch (Exception e) { 
     //e.printStackTrace(); 
     Log.e("Error : Location", "Impossible to connect to LocationManager", e); 
    } 

    return location; 
} 

public void updateGPSCoordinates() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
    } 
} 

public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       // TODO: Consider calling 
       // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
       // 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 Activity#requestPermissions for more details. 
       return; 
      } 
     } 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

public double getLatitude() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
    } 

    return latitude; 
} 

public double getLongitude() { 
    if (location != null) { 
     longitude = location.getLongitude(); 
    } 

    return longitude; 
} 

public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

public List<Address> getGeocoderAddress(Context context) { 
    if (location != null) { 
     Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
     try { 
      return geocoder.getFromLocation(latitude, longitude, 1); 
     } catch (IOException e) { 
      //e.printStackTrace(); 
      Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e); 
     } 
    } 

    return null; 
} 

public String getAddressLine(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 

     return address.getAddressLine(0); 
    } else { 
     return null; 
    } 
} 

public String getLocality(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 

     return address.getLocality(); 
    } else { 
     return null; 
    } 
} 

public String getSubLocality(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 

     return address.getSubLocality(); 
    } else { 
     return null; 
    } 
} 

public String getPostalCode(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 

     return address.getPostalCode(); 
    } else { 
     return null; 
    } 
} 

public String getCountryName(Context context) { 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) { 
     Address address = addresses.get(0); 

     return address.getCountryName(); 
    } else { 
     return null; 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 

    this.location = location; 

} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onConnected(Bundle connectionHint) { 
    isPlayServicesEnabled = true; 
    getLocation(); 
} 

@Override 
public void onConnectionSuspended(int cause) { 
    isPlayServicesEnabled = false; 
} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

}

這就是我所說的的AsyncTask:

public class Weather extends AppCompatActivity{ 

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.meteo_nuovo); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout); 
    setSupportActionBar(toolbar); 

    toolbar.setPadding(0, getStatusBarHeight(), 0, 0); 

    assert getSupportActionBar() != null; 

    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);  
    this.getSupportActionBar().setDisplayShowTitleEnabled(false); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
     getWindow().getDecorView().setSystemUiVisibility(
       View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
         | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 
    } 

    new WeatherApi(this).execute(); // the doInBackground method above is from this class 

} 

public int getStatusBarHeight() { 
    int result = 0; 

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { 
     int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); 
     if (resourceId > 0) { 
      result = getResources().getDimensionPixelSize(resourceId); 
     } 
    } 
    return result; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case android.R.id.home: 
      finish(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 

}

+0

從相關函數被調用的地方發佈你的活動代碼(相關),檢查你的gpstracker代碼 - [兩個if循環沒有幫助](http://stackoverflow.com/questions/23962769/android-gps -incorrect-location-data-on-query/24074771#24074771),爲後面的循環添加一個else。只是一個建議,即使找到了這個問題的答案,請嘗試切換到[FusedLocationProviderApi](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi) - 那麼你確實使用谷歌播放服務 – user2450263

+0

@ user2450263我試圖用_else_替換_if_語句,但現在我沒有得到它們後我重新啓動活動。 – Rick

+0

你可以顯示你的活動代碼,你在哪裏叫asynctask? – Rajesh

回答

1

我假設你正在呼籲doInBackground()方法在你的活動onCreate()方法,因此,如果GPS未啓用,則您的應用程序被重定向到GPS設置屏幕。

所以當你從GPS設置屏幕回來後,你的Activity恢復,所以它不會再次調用doInBackground()這就是爲什麼你沒有得到任何結果。

最簡單的解決方案是定義onResume()方法爲您ActivityonResume()調用doInBackground()而不是onCreate()所以當你活動的簡歷,這樣它會調用doInBackground()你又得到更新的結果。

您應該更新您的活動是否像這樣:

public class Weather extends AppCompatActivity{ 

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.meteo_nuovo); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout); 
    setSupportActionBar(toolbar); 

    toolbar.setPadding(0, getStatusBarHeight(), 0, 0); 

    assert getSupportActionBar() != null; 

    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);  
    this.getSupportActionBar().setDisplayShowTitleEnabled(false); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
     getWindow().getDecorView().setSystemUiVisibility(
       View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
         | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 
    } 
} 

@Override 
public void onResume(){ 
    super.onResume(); 
    new WeatherApi(this).execute(); // the doInBackground method above is from this class 

} 

public int getStatusBarHeight() { 
    int result = 0; 

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { 
     int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); 
     if (resourceId > 0) { 
      result = getResources().getDimensionPixelSize(resourceId); 
     } 
    } 
    return result; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case android.R.id.home: 
      finish(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 
} 

我希望它可以幫助你。

+0

我編輯了問題,以顯示我在哪裏打電話給_AsyncTask_ – Rick

+0

@Rick查看我的更新回答 – Rajesh

+0

完美答案! +1謝謝! ;) – Rick

1

使用getLastKnownLocation出現問題的原因,有時是因爲它可能需要一段時間它實際上找到lastKnownLocation。

嘗試使用onLocationChanged函數設置您的位置,這應該有效地消除此問題。

你可以做到這一點,如下所示:

@Override 
public void onLocationChanged(Location location) 
{ 
    this.location = location; 
} 

現在,每當你的位置有所改變(或首次發現時間)onLocationChanged事件將被調用,將您的GPSTracker位置變量設置爲定位時間傳入調用參數!

編輯:

試着改變你的GPSTracker類以下幾點:

public class GPSTracker extends Service implements LocationListener, ConnectionCallbacks { 
private final Context mContext; 

boolean isPlayServicesEnabled = false; 

boolean isGPSEnabled = false; 

boolean isNetworkEnabled = false; 

boolean canGetLocation = false; 

Location location; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters 

private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute 

protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
     } else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()); 

       Log.d("Network", "Network"); 

       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        updateGPSCoordinates(); 
       } 
      } 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

        Log.d("GPS Enabled", "GPS Enabled"); 

        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         updateGPSCoordinates(); 
        } 
       } 
      } 
     } 
    } catch (Exception e) { 
     //e.printStackTrace(); 
     Log.e("Error : Location", "Impossible to connect to LocationManager", e); 
    } 

    return location; 
} 

public void updateGPSCoordinates() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
    } 
} 

public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       // TODO: Consider calling 
       // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
       // 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 Activity#requestPermissions for more details. 
       return; 
      } 
     } 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

public double getLatitude() 
{ 
    if (location != null) 
    { 
     latitude = location.getLatitude(); 
    } 

    return latitude; 
} 

public double getLongitude() 
{ 
    if (location != null) 
    { 
     longitude = location.getLongitude(); 
    } 

    return longitude; 
} 

public boolean canGetLocation() 
{ 
    return this.canGetLocation; 
} 

public List<Address> getGeocoderAddress(Context context) 
{ 
    if (location != null) 
    { 
     Geocoder geocoder = new Geocoder(context, Locale.ENGLISH); 
     try 
     { 
      return geocoder.getFromLocation(latitude, longitude, 1); 
     } 
     catch (IOException e) 
     { 
      //e.printStackTrace(); 
      Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e); 
     } 
    } 

    return null; 
} 

public String getAddressLine(Context context) 
{ 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) 
    { 
     Address address = addresses.get(0); 

     return address.getAddressLine(0); 
    } 
    else 
    { 
     return null; 
    } 
} 

public String getLocality(Context context) 
{ 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) 
    { 
     Address address = addresses.get(0); 

     return address.getLocality(); 
    } 
    else 
    { 
     return null; 
    } 
} 

public String getSubLocality(Context context) 
{ 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) 
    { 
     Address address = addresses.get(0); 

     return address.getSubLocality(); 
    } 
    else 
    { 
     return null; 
    } 
} 

public String getPostalCode(Context context) 
{ 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) 
    { 
     Address address = addresses.get(0); 

     return address.getPostalCode(); 
    } 
    else 
    { 
     return null; 
    } 
} 

public String getCountryName(Context context) 
{ 
    List<Address> addresses = getGeocoderAddress(context); 
    if (addresses != null && addresses.size() > 0) 
    { 
     Address address = addresses.get(0); 

     return address.getCountryName(); 
    } 
    else 
    { 
     return null; 
    } 
} 

@Override 
public void onLocationChanged(Location location) 
{ 
} 

@Override 
public void onProviderDisabled(String provider) 
{ 
} 

@Override 
public void onProviderEnabled(String provider) 
{ 
} 

@Override 
public void onConnected(Bundle connectionHint) { 
    isPlayServicesEnabled = true; 
    getLocation(); 
} 

@Override 
public void onConnectionSuspended(int cause) { 
    isPlayServicesEnabled = false; 
} 

我相信可能會導致您的問題是,你不檢查,如果谷歌Play服務連接與否。在上面的代碼中,我實現了ConnectionCallbacks,幷包含onConnected和onConnectionSuspended覆蓋。現在,只有Play服務連接後纔會調用getLocation()。讓我知道這是否可行。

+0

我該怎麼做? – Rick

+0

編輯帖子以包含實施信息。 –

+0

我還沒有得到它的第一個,我不知道爲什麼 – Rick

2

據我所面對的這個問題,但我已經用我自己的方式解決了。

在你的GPSTracker類中做出一個方法。

public void onActivityResult(int requestCode, int resultcode, Intent data) { 

} 

現在用startActivityForResult代替startActivity開始活動,

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
mContext.startActivityForResult(intent, 0); 

現在您的活動,當你回到onActivityResult方法現在

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    gpsTracker.onActivityResult(requestCode, resultCode, data);// This line is more important 

    if (requestCode == 0) { 

     handler.sendEmptyMessage(0); 

    } 
} 

handler

android.os.Handler handler = new android.os.Handler(new android.os.Handler.Callback() { 
    @Override 
    public boolean handleMessage(Message message) { 
     try { 
       Location location = gpsTracker.getLocation(); 
       latitude = location.getLatitude(); 
       longitude = location.getLongitude(); 
     } catch (Exception e) { 
      Log.v("Error:", "Location is null"); 
     } 
     return false; 
    } 
}); 

使用這個,你可以immidiate位置,因爲我有。可能會有幫助。在我的情況下,它工作正常。

+0

對不起,我不明白我必須添加_onActivtiyResult_和_handler_方法。 – Rick

+0

在你的活動中,你應該使用! – Piyush

+0

@PiyushGupta我可以知道什麼是gpsTracker,它來自哪裏? – Rajesh