0

さまざまなインテントからサービスを呼び出したい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

    }

メインアクティビティの実装:

    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。解決 ?

4

0 に答える 0