Monday 12 August 2013

Get Speed from Gps

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <TextView
        android:id="@+id/gps_info"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical|center_horizontal"
        android:textSize="30dip"
        android:text="@string/gps_info"/>

</RelativeLayout>


then create below class for get gps location and calculate speed of vehicle.

MainActivity.java

package com.hazuu.android.gpsdemo;

import java.math.BigDecimal;
import java.math.RoundingMode;

import com.hazuu.android.gpsdemo.interfaces.Constants;
import com.hazuu.android.gpsdemo.interfaces.GPSCallback;
import com.hazuu.android.gpsdemo.managers.GPSManager;

import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements GPSCallback {
private GPSManager gpsManager = null;
private double speed = 0.0;
private AbsoluteSizeSpan sizeSpanLarge = null;
private AbsoluteSizeSpan sizeSpanSmall = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gpsManager = new GPSManager();

gpsManager.startListening(getApplicationContext());
gpsManager.setGPSCallback(this);

((TextView) findViewById(R.id.gps_info))
.setText(getString(R.string.gps_info));
}

@Override
public void onGPSUpdate(Location location) {
location.getLatitude();
location.getLongitude();
speed = location.getSpeed();

String speedString = String.valueOf(roundDecimal(convertSpeed(speed), 2));
String unitString = "km/h";

setSpeedText(R.id.gps_info, speedString + " " + unitString);
}

@Override
protected void onDestroy() {
gpsManager.stopListening();
gpsManager.setGPSCallback(null);

gpsManager = null;

super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

private double convertSpeed(double speed) {
return ((speed * Constants.HOUR_MULTIPLIER) * Constants.UNIT_MULTIPLIERS);
}

private double roundDecimal(double value, final int decimalPlace) {
BigDecimal bd = new BigDecimal(value);

bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
value = bd.doubleValue();

return value;
}

private void setSpeedText(int textid, String text) {
Spannable span = new SpannableString(text);
int firstPos = text.indexOf(32);

span.setSpan(sizeSpanLarge, 0, firstPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(sizeSpanSmall, firstPos + 1, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView tv = ((TextView) findViewById(textid));

tv.setText(span);
}


}

Build Constants interface 

Constants.java

package com.hazuu.android.gpsdemo.interfaces;

public interface Constants 
{
        public static final int TEXT_SIZE_SMALL = 15;
        public static final int TEXT_SIZE_LARGE = 80;
        public static final int DEFAULT_SPEED_LIMIT = 80;
        public static final int HOUR_MULTIPLIER = 3600;
        public static final double UNIT_MULTIPLIERS = 0.001;
}

Build GPSCallback interface

GPSCallback.java

package com.hazuu.android.gpsdemo.interfaces;

import android.location.Location;

public interface GPSCallback {
public abstract void onGPSUpdate(Location location);
}


then create GPSManager class for get all GpsUpdate data and convert in to kh/h form.

GPSManager.java

package com.hazuu.android.gpsdemo.managers;

import java.util.List;

import com.hazuu.android.gpsdemo.interfaces.GPSCallback;



import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class GPSManager
{
        private static final int gpsMinTime = 500;
        private static final int gpsMinDistance = 0;
        
        private static LocationManager locationManager = null;
        private static LocationListener locationListener = null;
        private static GPSCallback gpsCallback = null;
        
        public GPSManager()
        {       
                GPSManager.locationListener = new LocationListener()
                {
                        @Override
                        public void onLocationChanged(final Location location)
                        {
                                if (GPSManager.gpsCallback != null)
                                {
                                        GPSManager.gpsCallback.onGPSUpdate(location);
                                }
                        }
                        
                        @Override
                        public void onProviderDisabled(final String provider)
                        {
                        }
                        
                        @Override
                        public void onProviderEnabled(final String provider)
                        {
                        }
                        
                        @Override
                        public void onStatusChanged(final String provider, final int status, final Bundle extras)
                        {
                        }
                };
        }
        
        public GPSCallback getGPSCallback()
        {
                return GPSManager.gpsCallback;
        }
        
        public void setGPSCallback(final GPSCallback gpsCallback)
        {
                GPSManager.gpsCallback = gpsCallback;
        }
        
        public void startListening(final Context context)
        {
                if (GPSManager.locationManager == null)
                {
                        GPSManager.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                }
                
                final Criteria criteria = new Criteria();
                
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setSpeedRequired(true);
                criteria.setAltitudeRequired(false);
                criteria.setBearingRequired(false);
                criteria.setCostAllowed(true);
                criteria.setPowerRequirement(Criteria.POWER_LOW);
                
                final String bestProvider = GPSManager.locationManager.getBestProvider(criteria, true);
                
                if (bestProvider != null && bestProvider.length() > 0)
                {
                        GPSManager.locationManager.requestLocationUpdates(bestProvider, GPSManager.gpsMinTime,
                                        GPSManager.gpsMinDistance, GPSManager.locationListener);
                }
                else
                {
                        final List<String> providers = GPSManager.locationManager.getProviders(true);
                        
                        for (final String provider : providers)
                        {
                                GPSManager.locationManager.requestLocationUpdates(provider, GPSManager.gpsMinTime,
                                                GPSManager.gpsMinDistance, GPSManager.locationListener);
                        }
                }
        }
        
        public void stopListening()
        {
                try
                {
                        if (GPSManager.locationManager != null && GPSManager.locationListener != null)
                        {
                                GPSManager.locationManager.removeUpdates(GPSManager.locationListener);
                        }
                        
                        GPSManager.locationManager = null;
                }
                catch (final Exception ex)
                {
                        
                }
        }
}


then below permission are must be add in Androidmainfest.xml

 

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>



Androidmainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hazuu.android.gpsdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.hazuu.android.gpsdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4 comments: