Android中的位置始终返回null

时间:2015-07-27 17:52:26

标签: android

我是Android编程的开销者,我在使用NETWORK PROVIDER显示手机的当前位置时遇到了问题,我需要一些帮助。

以下是代码:

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

    txtLat = (TextView) findViewById(R.id.txtLat);
    txtLon = (TextView) findViewById(R.id.txtLon);

    Log.d("ADebugTag",  "WTF");

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            txtLat.setText(String.valueOf(location.getLatitude()));
            txtLon.setText(String.valueOf(location.getLongitude()));
        }

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

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    Log.d("ADebugTag",  "WTF END");
}   

我尝试将位置的纬度和经度设置为TextViews,但是当我尝试运行它时我的应用程序崩溃了。 此外,我试图打印完整的堆栈跟踪,但我找不到一种方法使其工作..

更新:感谢所有回复:D - 发布后我意识到我还应该发布主要活动的布局,以防万一。     

<TextView
    android:id = "@+id/txtLat"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="LATITUDINE" />
<TextView
    android:id = "@+id/txtLon"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtLat"
    android:text="LONGITUDINE" />

另外,我在调用onLocationChanged方法时尝试在logcat中打印一些东西,但是当我运行app时没有显示该消息,这意味着没有调用该方法。 我在使用Android 2.3.6的旧设备上运行此应用程序,也许这也是有用的信息。

3 个答案:

答案 0 :(得分:1)

您很可能缺少相应的应用权限。确保在清单文件中添加以下行:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

我不确定前两个,但肯定你必须拥有粗略和精细的位置权限。

答案 1 :(得分:0)

这是我在m个应用程序中重用的示例,使用自定义类来包装LocationListener:

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;


public class MyLocationListener implements LocationListener {

  // GLOBALS
  float currentLatitude     = 0;
  float currentLongitude    = 0;
  float currentAltitude     = 0;
  float currentAccuracy     = 0;
  float currentSpeed        = 0;
  float currentBearing  = 0;
  String currentProvider    = "";

  public MyLocationListener(Context context) {
        super();
  }

  // Define all LocationListener methods
  public void onLocationChanged(Location location) {

    currentLatitude  = (float)location.getLatitude();
    currentLongitude = (float)location.getLongitude();
    currentAltitude = (float)location.getAltitude();
    currentAccuracy  = (float)location.getAccuracy();
    currentSpeed = (float)location.getSpeed();
    currentBearing = (float)location.getBearing();
    currentProvider  = location.getProvider();

  }

  public void onProviderDisabled (String provider) { 
    //currentProvider = "";
    Log.v(TAG, "Provider is " + provider);
  }

  public void onProviderEnabled (String provider) { 
    //currentProvider = provider;
    Log.v(TAG, "Provider is " + provider);
  }

  public void onStatusChanged (String provider, int status, Bundle extras) {
    Log.v(TAG, "Status is " + status);
  }

  // Custom Methods

  public String getCurrentLatitude() {
      String lat = Float.toString(currentLatitude);
      return lat;
  }

  public String getCurrentLongitude() {
      String lon = Float.toString(currentLongitude);
      return lon;
  }

  public String getCurrentAltitude() {
      String alt = Float.toString(currentAltitude);
      return alt;
  }

  public String getCurrentAccuracy() {
      String acc = Float.toString(currentAccuracy);
      return acc;
  }

  public String getCurrentSpeed() {
      String spd = Float.toString(currentSpeed);
      return spd;
  }

} 

...然后在 onCreate

// GPS
        locationListener = new MyLocationListener(this); // instance of above class

// Runnable
        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                handler.postDelayed(this, REFRESH_RATE);

                // Get Data

                float lat = Float.parseFloat(locationListener.getCurrentLatitude());
                float lon = Float.parseFloat(locationListener.getCurrentLongitude());



                // Update Text
                ActualLatitude.setText(locationListener.getCurrentLatitude());
                ActualLongitude.setText(locationListener.getCurrentLongitude());

            }
        };
        handler.postDelayed(runnable, REFRESH_RATE);

..然后在 onResume

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

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, REFRESH_RATE, 5, locationListener);
    locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

..然后在 onDestroy

@Override
public void onDestroy() {
    super.onDestroy();

    // Kill Runnable
    handler.removeCallbacks(runnable);

    // Stop GPS
    locationManager.removeUpdates(locationListener);
    locationManager = null;

}

其他一些说明:

  • 确保您已在AndroidManifest中请求COARSE_LOCATION和/或FINE_LOCATION
  • 仔细检查你的文本视图的id - 你说它崩溃了,没有看到堆栈跟踪,因为我们知道所有位置的东西都很好但是它在NPE上崩溃了!

答案 2 :(得分:0)

这是我目前在android中获取用户位置的工作代码:

"%%Z"

现在,您注意到我在此处使用EventBus库将结果发布到相应的活动/片段。

在您的活动或片段中,您获取应用程序实例(getApplication())并调用acquireUserCoordinates()方法,然后您可以覆盖onEvent(EventClassHere事件),然后分别轻松更新UI(如dismiss对话框)。

您可以在此处找到EventBus:EventBus

我希望这会对你有所帮助。

祝你好运,编码愉快!