无法从location.getSpeed()获取当前速度

时间:2014-12-23 04:50:52

标签: android gps

我正在尝试获取纬度,经度,当前地址,当前速度并每隔5分钟发送到服务器。我可以得到lat,long,地址。但我无法从location.getSpeed()获得当前速度。 在此我附上了我的全部代码。请查看并向我提出解决问题的宝贵建议

public class MainActivity extends FragmentActivity implements LocationListener {

    private GoogleMap googleMap;

    private LocationManager locationManager;
    private String provider;
    Location location;

    UserSessionManager session;

    private Handler customHandler = new Handler();

    String currentdatetime_tosend, latitude_tosend, logitude_tosend,
            address_tosend, speed_tosend, username_tosend, startTime_tosend;    

    Boolean isInternetAvail = false;
    ConnectionCheck conChk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle(GlobalConstants.loginDriverName);
        System.out.println("GlobalConstants.loginDriverName==> "+GlobalConstants.loginDriverName);
        session = new UserSessionManager(getApplicationContext());
        try {
            initilizeMap();
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setZoomControlsEnabled(false);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);
            googleMap.getUiSettings().setCompassEnabled(true);
            googleMap.getUiSettings().setRotateGesturesEnabled(true);
            googleMap.getUiSettings().setZoomGesturesEnabled(true);
            conChk = new ConnectionCheck(getApplicationContext());
            GetLocaion();           

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void AddMarker(double latitude, double longitude, String driverName) {
        googleMap.clear();
        MarkerOptions marker = new MarkerOptions().position(
                new LatLng(latitude, longitude)).title(driverName);

        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_car));

        googleMap.addMarker(marker);

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(latitude, longitude)).zoom(15).build();

        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            Double lat = (Double) (location.getLatitude());
            Double lng = (Double) (location.getLongitude());
            speed_tosend = Float.toString(location.getSpeed());
            Toast.makeText(getApplicationContext(),
                    "Speed==> " + speed_tosend.toString() + "",
                    Toast.LENGTH_SHORT).show();
            latitude_tosend = lat.toString();
            logitude_tosend = lng.toString();
            getAddress();
            AddMarker(lat, lng, GlobalConstants.loginDriverName);
            if (conChk.isConnectingToInternet())
                new SendDetailsInBackground().execute();
        } else
            Toast.makeText(getApplicationContext(),
                    "Getting Location.. Please Wait..", Toast.LENGTH_SHORT)
                    .show();

    }

    private void BackgroundProcess() {
        customHandler.postDelayed(updateTimerThread, 0);
    }

    private Runnable updateTimerThread = new Runnable() {

        public void run() {
            GetLocaion();           
            customHandler.postDelayed(this, 30000);
        }
    };

    private void StartTheProcess() {
        BackgroundProcess();
    }

    private void StopGetingLocation() {
        customHandler.removeCallbacks(updateTimerThread);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

    private void GetLocaion() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            provider = locationManager.getBestProvider(criteria, false);
            location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
                Toast.makeText(getApplicationContext(), "Location Activated",
                        Toast.LENGTH_SHORT).show();
            } else {                
                Toast.makeText(getApplicationContext(),
                        "No location found..!!", Toast.LENGTH_SHORT).show();

            }
            Toast.makeText(getApplicationContext(), "GPS IS Ennabled..!!",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    private void initilizeMap() {
        if (googleMap == null) {

            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();

            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.startGettingLocation) {
            startTime_tosend = getDateTime();
            StartTheProcess();
            return true;
        }
        if (id == R.id.stopGetingLocation) {
            StopGetingLocation();
            return true;
        }

        if (id == R.id.logout) {
            exit();
        }
        return super.onOptionsItemSelected(item);
    }

    private String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
    }

    class SendDetailsInBackground extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("currentdatetime",
                    startTime_tosend));
            params.add(new BasicNameValuePair("driver_mobile",
                    GlobalConstants.loginDriverNumber));
            params.add(new BasicNameValuePair("username",
                    GlobalConstants.loginDriverName));
            params.add(new BasicNameValuePair("lattitude", latitude_tosend));
            params.add(new BasicNameValuePair("longtitude", logitude_tosend));
            params.add(new BasicNameValuePair("currentaddress", address_tosend));
            params.add(new BasicNameValuePair("currentspeed", speed_tosend));

            String json = sendToServer(GlobalConstants.url_pass_tripdetail,
                    params);

            Log.d("Create Response", json.toString());
            return null;
        }

        protected void onPostExecute(String file_url) {
        }

    }

    public String sendToServer(String url, List<NameValuePair> params) {
        String TAG = "";

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity);
            System.out.println("Response==> " + response);
            TAG = response;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return TAG;
    }

    private void getAddress() {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());

        try {
            List<Address> addresses = geocoder.getFromLocation(
                    Double.parseDouble(latitude_tosend),
                    Double.parseDouble(logitude_tosend), 1);
            StringBuilder sb = new StringBuilder();
            if (addresses.size() > 0) {
                Address address = addresses.get(0);

                for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                    sb.append(address.getAddressLine(i) + ",");
                Toast.makeText(getApplicationContext(), "Address Found..!!!",
                        Toast.LENGTH_LONG).show();
                address_tosend = sb.toString();

            } else {
                Toast.makeText(getApplicationContext(), "Address is empty!",
                        Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "No Address returned!",
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void exit() {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Logout")
                .setMessage("Are you sure you want to Logout?")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                session.logoutUser();
                                StopGetingLocation();
                                finish();
                            }
                        }).setNegativeButton("No", null).show();
    }

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

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

0 个答案:

没有答案