2015-02-10 157 views
1

我想學習Android上的位置服務工作。我使用了我找到的最簡單的代碼,並試着學習它如何工作。但問題是,當我想把座標放到textView。GPS固定時獲取座標 - Android

這裏是代碼:

package com.example.bakalarka; 

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.widget.TextView; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 


    public class GPSActivity extends FragmentActivity { 

     private GoogleMap mMap; 
     private TextView txtLat; 
     private TextView txtLng; 
     private TextView category; 

     protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_gps); 
       category = (TextView)findViewById(R.id.category); 
       txtLat = (TextView)findViewById(R.id.tv_latitude); 
       txtLng = (TextView)findViewById(R.id.tv_longitude); 
       category.setText(getIntent().getStringExtra("kategorie")); 
       setUpMapIfNeeded(); 
     } 

     @Override 
     protected void onResume() { 
      super.onResume(); 
      setUpMapIfNeeded(); 
     } 

     private void setUpMapIfNeeded() { 
      // Do a null check to confirm that we have not already instantiated the map. 
      if (mMap == null) { 
       // Try to obtain the map from the SupportMapFragment. 
       mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
         .getMap(); 
       // Check if we were successful in obtaining the map. 
       if (mMap != null) { 
        setUpMap(); 
       } 
      } 
     } 

     private void setUpMap() { 


      // Enable MyLocation Layer of Google Map 
      mMap.setMyLocationEnabled(true); 

      // Get LocationManager object from System Service LOCATION_SERVICE 
      LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

      if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
       buildAlertMessageNoGps(); 
      } 

      // Create a criteria object to retrieve provider 
      Criteria criteria = new Criteria(); 

      // Get the name of the best provider 
      String provider = locationManager.getBestProvider(criteria, true); 

      // Get Current Location 
      Location myLocation = locationManager.getLastKnownLocation(provider); 

      // set map type 
      mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

      // Get latitude of the current location 
      double latitude = myLocation.getLatitude(); 

      // Get longitude of the current location 
      double longitude = myLocation.getLongitude(); 

      // Create a LatLng object for the current location 
      LatLng latLng = new LatLng(latitude, longitude); 

      String stringDoubleLat = Double.toString(latitude); 
      txtLat.setText(stringDoubleLat); 
      String stringDoubleLng = Double.toString(longitude); 
      txtLng.setText(stringDoubleLng); 

      // Show the current location in Google Map 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

      // Zoom in the Google Map 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 

     } 

     private void buildAlertMessageNoGps() { 
      final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") 
        .setCancelable(false) 
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
         public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
          startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
         } 
        }) 
        .setNegativeButton("No", new DialogInterface.OnClickListener() { 
         public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
          dialog.cancel(); 
         } 
        }); 
      final AlertDialog alert = builder.create(); 
      alert.show(); 

     } 

    } 

所以問題是,當GPS被關閉,應用程序帶給我當然不準確的座標,因爲我越來越GPS座標找到我的位置之前。

在GPS找到我的位置後,如何獲取座標並將其放置在藍色點上?

編輯:

package com.example.locationlistener; 


import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.LatLng; 


import android.support.v4.app.FragmentActivity; 
import android.widget.TextView; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 


public class MainActivity extends FragmentActivity { 

    private GoogleMap mMap; 
    private TextView txtLat; 
    private TextView txtLng; 
    private LocationManager locationManager; 

    //private TextView category; 

    protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      //category = (TextView)findViewById(R.id.category); 
      txtLat = (TextView)findViewById(R.id.tv_latitude); 
      txtLng = (TextView)findViewById(R.id.tv_longitude); 
      //category.setText(getIntent().getStringExtra("kategorie"));*/ 

      // Get LocationManager object from System Service LOCATION_SERVICE 
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener); 


    } 
    private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      String stringDoubleLat = Double.toString(location.getLatitude()); 
      txtLat.setText(stringDoubleLat); 
      String stringDoubleLng = Double.toString(location.getLongitude()); 
      txtLng.setText(stringDoubleLng); 
     } 

     public void onProviderDisabled(String provider){ 

     } 

     public void onProviderEnabled(String provider){} 

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

     @Override 
    protected void onResume() { 
     super.onResume(); 
     setUpMapIfNeeded(); 

    } 

    private void setUpMapIfNeeded() { 
     // Do a null check to confirm that we have not already instantiated the map. 
     if (mMap == null) { 
      // Try to obtain the map from the SupportMapFragment. 
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
        .getMap(); 
      // Check if we were successful in obtaining the map. 
      if (mMap != null) { 
       setUpMap(); 
      } 
     } 
    } 

    private void setUpMap() { 


     // Enable MyLocation Layer of Google Map 
     mMap.setMyLocationEnabled(true); 




     if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      buildAlertMessageNoGps(); 
     } 

     // Create a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setPowerRequirement(Criteria.POWER_HIGH); 

     // Get the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 

     // Get Current Location 
     Location myLocation = locationManager.getLastKnownLocation(provider); 

     // set map type 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     // Get latitude of the current location 
     double latitude = myLocation.getLatitude(); 

     // Get longitude of the current location 
     double longitude = myLocation.getLongitude(); 

     // Create a LatLng object for the current location 
     LatLng latLng = new LatLng(latitude, longitude); 

     String stringDoubleLat = Double.toString(latitude); 
     txtLat.setText(stringDoubleLat); 
     String stringDoubleLng = Double.toString(longitude); 
     txtLng.setText(stringDoubleLng); 

     // Show the current location in Google Map 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

     // Zoom in the Google Map 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 


    } 


    private void buildAlertMessageNoGps() { 
     final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage("Your GPS seems to be disabled, do you want to enable it?") 
       .setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
         startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
        } 
       }) 
       .setNegativeButton("No", new DialogInterface.OnClickListener() { 
        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
         dialog.cancel(); 
        } 
       }); 
     final AlertDialog alert = builder.create(); 
     alert.show(); 

    } 

} 

所以,我實現位置監聽器(我希望我做了好),但它看起來該應用程序的作品。如果我理解的很好,首先我得到了比UpdatePosition更快的lastKnownPosition。然後LocationListener在更改位置時調用onLocationChanged方法。我希望我能理解它。

怎麼可能我不需要onCreate中的setUpMapIfNeeded方法?我認爲onResume只適用於應用程序背景。

回答

2

你的代碼的檢查後,我建議你們兩個更正:

1 - 滿足您criteria。您將它傳遞給locationManager實例。 2 - 使用LocationListener API來實現你想要的。你可以找到here一些幫助。

編輯:onCreate方法中刪除呼叫setUpMapIfNeeded()。這實際上被調用兩次(在onCreate和onResume())。

+0

就像nekoexmachina一樣。非常感謝你。我如何寫上面我需要明天才能理解好,並在我的代碼中做出一點點順序。 – Bulva 2015-02-10 20:15:40

+0

如果您有更多不明白的地方,請編輯您的問題。如果可以的話,我會幫你的。 – 2015-02-11 09:33:54

+0

我對你的幫助和米哈伊爾克魯托夫的幫助非常沉重。我用一個問題編輯了我的答案。我有更多的問題,但我忘了他們;-)。如果可以的話,我會給你和米哈伊爾的名聲,但我現在還不能。 – Bulva 2015-02-11 14:00:45

2

至少使用onLocationChanged方法實現Location Listener。 http://developer.android.com/reference/android/location/LocationListener.html

+0

非常感謝你,我實現了這個類,並且位置改變的效果很好 - 只有座標有一些更多的數字,比如16.653453333338。明天我會嘗試更好地理解代碼。我很樂意爲你提供幫助,如果我有麻煩,我會在明天寫信給你。 – Bulva 2015-02-10 20:13:58

0

添加到修改的問題新的響應:

活動對Android有一個適當的lyfecycle。你可以檢查here。 onResume在活動來自後臺時調用,而且在創建時(在onCreate調用之後)。你可以檢查我提供的鏈接。

我也檢查了你的代碼,對我來說似乎很好。如果出現一些意想不到的行爲,請問:)

+0

Thx很多在developer.android.com上的漂亮圖片。我在4個月前開始學習Java和Android,但過去兩個月我沒有太多時間,所以我忘了很多事情。我應該重讀基礎知識。如果我有問題,我會問你。 Thx再次:-) – Bulva 2015-02-11 14:53:19

+0

@Bulva歡迎您! :) – 2015-02-11 14:56:04

+0

嗨澤路易斯,我正在測試這個應用程序在一些設備上的一些變化。我在某些設備上使用setUpMapIfNeeded獲取nullpointerexception(9個設備中有3個給我例外)。所有設備都有Android 4及更高版本。你知道什麼可能是問題嗎?我沒有錯誤行,但我怎麼說它是在setUpMapIfNeeded中。如果你知道它有什麼問題,我會創建一個新的線程,我會給你檢查一個正確的答案。再次感謝 – Bulva 2015-04-06 22:13:01