如何在服务中运行onLocationChanged

时间:2018-05-03 01:46:55

标签: android google-maps service android-lifecycle

我刚进入android,请帮忙。 我试图在服务中运行onLocationChanged(Location location)。 这样它就会一直制作标记,直到点击停止按钮。

public class MyService extends Service implements LocationListener {
    // variable peta
    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    private GoogleMap mMap;
    Location location;

    // parameter untuk di masukin ke database
    TextView tvlattitude;
    TextView tvlongitude;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onLocationChanged(location);
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLocationChanged(Location location) {
        double lattitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                .position(latLng)
                .title("Kamu disini"));

        tvlattitude.setText(""+lattitude);
        tvlongitude.setText(""+longitude);
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

这是我试过的,但是它说location上的空指针异常 是什么原因呢?需要帮助。

0 个答案:

没有答案