Thursday, May 3, 2012

Calculate Device Moving Speed Programmatically

so this evening i would like to share with you new thing what i have learn..

some time we need to calculate moving speed of our android mobile device.

this example will calculate the location coordinates latitude-longitude after every 5 seconds gap.
and then calculate the speed of device in m/s.
all work done in background by the service.

so i we need to do is install this app into mobile and close now it started a background service
and calculate the speed forever..
[you can create without any activity also, but i have created an activity ans started the service from activity]

let's begin the coding, first of all we need to create a simple project having single activity like this
DeviceMovingSpeed.java
  
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class DeviceMovingSpeed extends Activity// implements Runnable
{
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v("Debug", "Activity started..");
Intent myIntent=new Intent(this,MyService.class);
startService(myIntent);
}
}

Now we need to create a service where we will handle all the stuff creating a thread Getting current location calculating coordinates latitude-longitude calculating distance and device moving speed
MyService.java
  
package com.rdc;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service
{
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
static final Double EARTH_RADIUS = 6371.00;

private boolean gps_enabled = false;
private boolean network_enabled = false;

private Handler handler = new Handler();
Thread t;

@Override
public IBinder onBind(Intent intent) {return null;}
@Override
public void onCreate() {}
@Override
public void onDestroy() {}
@Override
public void onStart(Intent intent, int startid) {}
@Override
public int onStartCommand(Intent intent, int flags, int startId){

Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();

final Runnable r = new Runnable()
{ public void run()
{
Log.v("Debug", "Hello");
location();
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(r, 5000);
return START_STICKY;
}

public void location(){
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){}
Log.v("Debug", "in on create.. 2");
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
Log.v("Debug", "Enabled..");
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
Log.v("Debug", "Disabled..");
}
Log.v("Debug", "in on create..3");
}

private class myLocationListener implements LocationListener
{
double lat_old=0.0;
double lon_old=0.0;
double lat_new;
double lon_new;
double time=10;
double speed=0.0;
@Override
public void onLocationChanged(Location location) {
Log.v("Debug", "in onLocation changed..");
if(location!=null){
locManager.removeUpdates(locListener);
//String Speed = "Device Speed: " +location.getSpeed();
lat_new=location.getLongitude();
lon_new =location.getLatitude();
String longitude = "Longitude: " +location.getLongitude();
String latitude = "Latitude: " +location.getLatitude();
double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);
speed = distance/time;
Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
+distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
lat_old=lat_new;
lon_old=lon_new;
}
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}

public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
double Radius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
}

now come to AndroidManifest.xml
  






















okay!! that's it.. now run the application toast will appear to say :-
"current coordinates"
"distance if device is moving"
"and speed of device in m/s (meter/seconds)"

 cheers!!

 I'd love to hear your thoughts!

Labels: , , , , , ,

Friday, January 13, 2012

Get Current Location coordinates , City name

Sometime we need to get  GPS  coordinates in android. so today i am going to write step by step simple tutorial How can we get location coordinates using GPS in android mobile.

also through coordinate we can calculate current location more details like City Name.

Note: I have tested this app on My Android Mobile and its working fine.
But when you test this app, enable your gps settings in mobile, you need to change current location like 10-20 meter so you will get the coordinates, so need to move with the installed app mobile device.

What this app does?
  • Check gps is enable or disable.
  • Get gps coordinates.
  • Get the current city name.
okay! so let's try this small app

 -------------------------------------------
App Name: GetCurrentLocation
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: GetCurrentLocation
-------------------------------------------


GetCurrentLocation.java


package com.rdc;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class GetCurrentLocation extends Activity
implements OnClickListener {

private LocationManager locationMangaer=null;
private LocationListener locationListener=null;

private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;

private static final String TAG = "Debug";
private Boolean flag = false;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);

pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);

editLocation = (EditText) findViewById(R.id.editTextLocation);

btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);

locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

}

@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {

Log.v(TAG, "onClick");

editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");

pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();

locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);

} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}

}

/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;

} else {
return false;
}
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {

editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);

/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}

String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}

@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.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Current Location and City Name"
android:layout_weight="0.20"
android:gravity="center"
android:textSize="20sp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:id="@+id/editTextLocation"
android:editable="false">
<requestFocus></requestFocus>
</EditText>
<LinearLayout
android:id="@+id/layButtonH"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="@+id/btnLocation"></Button>
</LinearLayout>
<LinearLayout
android:id="@+id/layloadingH"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:layout_width="fill_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:id="@+id/progressBar1"
android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rdc"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />

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

<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".GetCurrentLocation"
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>

The output Screen will be like this..


You can download the complete source code zip file here : GetCurrentLocation

 cheers!!

I'd love to hear your thoughts!

Labels: , , , , ,