2015-02-10 107 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