Android locationManager空指针异常? (如何传递上下文?)

时间:2011-10-11 10:37:49

标签: java android gps locationmanager

我在这里遇到问题,我无法让它工作...... 我想获得最新的gps位置,但我得到的只是空指针异常。 它适用于第一类GPSActivity,但不适用于第二类SmsReceiver。

我读到这可能是因为我必须将Context传递给第二课但我不知道如何......请帮忙!

代码如下:

GPSActivity.class

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class GPSActivity extends Activity {
  long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
  long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in Milliseconds

  LocationManager locationManager;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);  
    locationManager = 
      (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.getAllProviders();
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener());

  }    

  public void showCurrentLocation() {
    Location location = 
      locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
      String message = String.format(
              "Current Location \n Longitude: %1$s \n Latitude: %2$s",
              location.getLongitude(), location.getLatitude());
      Toast.makeText(GPSActivity.this, message,
              Toast.LENGTH_LONG).show();
    }
  }
}

(我剥离了一些代码)

现在,我可以调用showCurrentLocation,它会向我显示long和lat值。

我怎么能在这里这样做:

SmsReceive.class(收到短信时,发送gps坐标)

import ...
public class SmsReceiver extends BroadcastReceiver
{   


  @Override
  public void onReceive(Context context, Intent intent) 
  {
    GPSActivity myGPS;
    myGPS = new GPSActivity();

    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    if (bundle != null) {
      //HERE I GET THE NULL POINTER EXCEPTION
      Location loc =
        myGPS.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      double varLong = loc.getLongitude();
      double varLat = loc.getLatitude();
      String locationData = "LONG: " + varLong+ " LAT: " + varLat;
      Toast.makeText(context, locationData, Toast.LENGTH_SHORT).show();
    }
  }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

在smsReceiver类中声明一个新的locationManager并使用以下行

mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
 Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

答案 1 :(得分:0)

创建扩展服务的One类,并在此实现GPS任务,因为在Activity中将停止/暂停/销毁,并且每次都无法获取。服务将在后台运行,因此您可以随时获取GPS坐标,并将位置对象定义为公共静态,以便您可以在应用程序的任何位置使用。