Android Tutorial For Beginners

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Android Tutorial : Android get current GPS location Página 1 de 12

Compartilhar 3 mais Próximo blog» Criar um blog Login

Android Tutorial
Android Tutorial for beginners

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 2 de 12

TUESDAY, APRIL 2, 2013

FOLLOWERS
Android get current GPS location

You can Find location either GPS_PROVIDER or NETWORK_PROVIDER

Overview of location services in Android , LocationManager class at the heart of location services in
Android.

Here is one example which try to find location using GPS , if your GPS not available then try to use
network for find location

Demo Code

Activity - AndroidGPSTrackingActivity.java

public class AndroidGPSTrackingActivity extends Activity { FOLLOW BY EMAIL

Button btnShowLocation;
Submit
// GPSTracker class
GPSTracker gps;
WHAT VERSION OF ANDROID IS BEST ?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) { BEAT READ TUTORIAL LIST
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this); Android get current GPS location

// check if GPS enabled Android Interview Questions and Answer


if(gps.canGetLocation()){
Android Upload Video in server
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Android Phone call history/log
programmatically
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude
Android Internal and External storage
+ "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location Android Notifications
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings Android get lat and long from address
gps.showSettingsAlert();
} Android Turn ON wifi programmatically

} Android Enable GPS (Check and prompt


}); user to enable GPS)
}
Android Toast notification show Different
} Gravity

ANDROID TUTORIAL
Android Fundamentals
Detect Battery Info.
Android Enable GPS (Check and prompt
user to enable GPS)
Android Location New Features
Android Notifications

TOP LINKS
Advance Android
Android Development Forum
Android Tutorials
Hello Android
Official Android Developers Blog
GPSTracke.java

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 3 de 12

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status GOOGLE+


boolean isGPSEnabled = false; Nirav Ranpara

// flag for network status Add to circles


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;
6 have me in circles View all

Location location; // location


double latitude; // latitude
double longitude; // longitude TOTAL PAGEVIEWS

// The minimum distance to change Updates in meters 32,028


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds BLOG ARCHIVE


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
▼ 2013 (10)
// Declaring a Location Manager ► August (1)
protected LocationManager locationManager; ► May (3)

public GPSTracker(Context context) { ▼ April (2)


this.mContext = context; Android Notifications
getLocation();
} Android get current GPS location

public Location getLocation() { ► March (4)


try {
locationManager = (LocationManager) mContext ► 2012 (5)
.getSystemService(LOCATION_SERVICE);

// getting GPS status ANDROID


isGPSEnabled = locationManager
Basics (1)
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Battery (1)
// getting network status
Camera (1)
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER); GPS (2)
Interview Questions (1)
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled Location (1)
} else { Map API (1)
this.canGetLocation = true;
Mapview (1)
if (isNetworkEnabled) {
locationManager.requestLocationUpdates( Notifications (1)
LocationManager.NETWORK_PROVIDER, Phone Call (1)
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Storage (1)
Log.d("Network", "Network"); Toast (1)
if (locationManager != null) {
Upload File (1)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); wifi (1)
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

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

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 4 de 12

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title


alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 5 de 12

@Override
public void onProviderEnabled(String provider) {
}

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

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

Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button android:id="@+id/btnShowLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>

</RelativeLayout>

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


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

Posted by nirav ranpara at 12:02 AM


+3 Recommend this on Google

Labels: GPS

13 comments:

Señor Web April 2, 2013 at 8:26 AM


muy buen tutorial, esta bueno para obtener la ubicacion por gps.

saludos cordiales
Consigue moviles dual sim al mejor precio
Reply

Anonymous June 12, 2013 at 3:13 PM


tienes alguna opción para descargar el código
Reply

Gilles Phan July 2, 2013 at 2:34 PM


Good, it's really usefull for discover how to test the geolocalisation but I think you
can slightly optimize your code using "if(isNetworkEnabled){...}else if
(isGPSEnabled){...}" instead of "if(isNetworkEnabled){...} if(isGPSEnabled){...}".
Unless it is done on purpose ! ^^

Reply

Anonymous July 4, 2013 at 9:31 AM


Good tutorial.
Can you export the project to us?
Reply

Anonymous July 8, 2013 at 1:06 AM

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 6 de 12

Crazy that Google doesn't provide any example code with their documentation...
this worked a treat though, thanks
Reply

xXxOlivierxXx July 28, 2013 at 9:49 PM


If you try to find these coordinates they lead to the Google Headquarters on
Mountain View XD.
Thanks for the tutorial.
Reply

Anonymous August 12, 2013 at 7:31 AM


thanks for the tutorial! However after clicking the show location button, im getting
the dialog box of asking me to enable the GPS location service even after i have
turned on the GPS. Any clues of why??
Reply

Ajay Prasad August 19, 2013 at 7:26 AM


Thanks for this tutorial, by inspiring with this tutorial i have created a program in
which GPS running in services, my program running well but my problem is
whenever i am driving for few minutes its work fine its update longitude and
latitude but after some time this will not updating longitude and latitude and
terminate my program if you have any idea why this is happen please guide me
with solution thanks in advance
Reply

Anonymous September 18, 2013 at 12:20 AM


great work.....please provide the source code.
Reply

Anonymous September 28, 2013 at 1:08 AM


thanx a lot ... just what i needed ... !!!
Reply

Imran Khokhar October 1, 2013 at 8:20 AM


This comment has been removed by the author.
Reply

Anonymous October 1, 2013 at 8:21 AM


GPS Provider does not give coordinates it give lat:0 and long:0!!! help me
Reply

David Souza October 2, 2013 at 9:39 AM


Good tutorial.
Reply

Comment as: Select profile...

Publish Preview

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 7 de 12

Links to this post


Create a Link

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

Picture Window template. Powered by Blogger.

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 8 de 12

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 9 de 12

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 10 de 12

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 11 de 12

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013
Android Tutorial : Android get current GPS location Página 12 de 12

http://niravranpara.blogspot.com.br/2013/04/android-get-current-gps-location.html 08/10/2013

You might also like