我想GPS
从不同的意图调用服务(我需要 GPS 持续运行)
Gps
服务实现:
public class GpsService extends Service implements LocationListener{
private final IBinder mBinder = new MyBinder();
private Location loc;
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public Location getLocation(){
return loc;
}
@Override
public void onCreate() {
super.onCreate();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public class MyBinder extends Binder {
GpsService getService() {
return GpsService.this;
}
}
@Override
public void onLocationChanged(Location location) {
loc.set(location);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
Main Activity的实现:
public class MainActivity extends FragmentActivity {
GpsService gps;
Location loc;
ServiceConnection sCon = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
gps = ((GpsService.MyBinder)service).getService();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent gpsIntent = new Intent(this,ListenLocationService.class);
bindService(gpsIntent, sCon, Context.BIND_AUTO_CREATE);
loc=gps.getLocation();
}
当我尝试使用gps.getLocation()
它时会抛出一个nullException
. 解决方案 ?