我在调用NullPointerException
时遇到getSystemService()
。我之前检查了一些帖子,但无法弄清楚它失败的原因。
public class GetGyroInfo extends Service implements LocationListener{
private float mLongAccl;
private float mLatAccl;
private static final long MIN_TIME_BW_UPDATES = 100; // 100 millisecond
//Declaring a location manager
private LocationManager mLocationManager = null;
private Location mLocation = null;
private static final String TAG = "ADAS_GetGyroInfo";
public void getLocation(Context context){
//Note: getApplicationContext returns NULL inside this constructor. Reason not clear.
//Create a registor for location updates
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
...
}
上面的类在以下类中初始化:
public class ABCService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sendStatusBroadcast(true);
//Registor location service.
mgetGyroInfo = new GetGyroInfo();
mgetGyroInfo.getLocation();
}
我尝试了以下代码并且成功了:
mgetGyroInfo.getLocation(getApplicationContext());
所以我的问题是,为什么我必须将ABCService
类的上下文传递给GetGyroInfo
?为什么我不能在GetGyroInfo
本身内部获取上下文?