Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current location in android programatically?

I'm trying to make a simple application on android to get the current location using GPS or network provider(WIFI or tower) but I'm facing so issues while trying to make it run on the android. It won't start it gave me an exception, I don't know why.

This is the code. It's so simple, because I want to test getting the location & later I will add some features & functionality..

the main:

package com.GpsTesting;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class GPS_TestActivity extends Activity{
    /** Called when the activity is first created. */
    String location_text="";

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


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

     // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
              // Called when a new location is found by the network location provider.

                if (location != null) {
                    double lat = location.getLatitude();
                    double lng = location.getLongitude();

                    location_text= "latitude: "+lat+"longitude: "+lng;

                    Toast.makeText(getApplicationContext(), location_text, Toast.LENGTH_SHORT).show();

                }
            }

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

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
          };



        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);

    }

}

the manifest:

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

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:permission="android.permission.ACCESS_FINE_LOCATION">
        <activity android:name=".GPS_TestActivity"
                  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>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


</manifest>

So, Is there is a problem in the code?? I'm doing that using online tutorial (from android dev & other sites).

Thanks alot.

Notes Added:

**I have really weared thing. I try to run the application using the eclipse way(connecting my device through USB & run the application into the device instead of the application).. when I tried this way, the application run just fine without problem !!! while using the old way(sending the .apk through email & then installing it from the phone, it keeps giving me the exception !!) can any one explain for me why is that happening ?? Am I missing something ?? since, I'm knew in the android development. so, I'm afraid that I'm missing a point...

Note: I'm sending through the E-mail the .apk file that is in the bin folder(that is signed with eclipse, for testing purpose)... I tried with another simple application just to make sure that the .apk file that is available in the bin folder the right onw(for testing) or not, & it does works.. so, the apk file is just fine... but why for the network application its not working while in the eclipse it does work ?? Thanks in advance ;)**

Solved ;)

The solution for the problem i added a permission before in the manifest in the application tag

android:permission="android.permission.ACCESS_FINE_LOCATION"

and it was duplicate since its already been added below(or because its in the wrong place). So, i deleted it & it is running fine.

Thank you very much guys

like image 876
Q8Y Avatar asked Jul 15 '11 12:07

Q8Y


2 Answers

First of all I check what providers are enabled. Some may be disabled on the device, some may be disabled in application manifest. If any provider is available I start location listeners and timeout timer. It's 20 seconds in my example, may not be enough for GPS so you can enlarge it. If I get update from location listener I use the provided value. I stop listeners and timer. If I don't get any updates and timer elapses I have to use last known values. I grab last known values from available providers and choose the most recent of them.

   MyLocation myLocation = new MyLocation();

   private void locationClick() {
    myLocation.getLocation(this, locationResult);
   }

public LocationResult locationResult = new LocationResult() {

    @Override
    public void gotLocation(final Location location) {
        //Got the location!
    }
};

And here's MyLocation class:

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(lm==null)
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gps_enabled && !network_enabled)
        return false;

    if(gps_enabled)
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,  locationListenerGps);
    if(network_enabled)
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,  locationListenerNetwork);
    timer1=new Timer();
    timer1.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
         lm.removeUpdates(locationListenerGps);
         lm.removeUpdates(locationListenerNetwork);

         Location net_loc=null, gps_loc=null;
         if(gps_enabled)
             gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
         if(network_enabled)
             net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

         //if there are both values use the latest one
         if(gps_loc!=null && net_loc!=null){
             if(gps_loc.getTime()>net_loc.getTime())
                 locationResult.gotLocation(gps_loc);
             else
                 locationResult.gotLocation(net_loc);
             return;
         }

         if(gps_loc!=null){
             locationResult.gotLocation(gps_loc);
             return;
         }
         if(net_loc!=null){
             locationResult.gotLocation(net_loc);
             return;
         }
         locationResult.gotLocation(null);
    }
}

public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
}
}


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
like image 104
Nikunj Patel Avatar answered Sep 18 '22 02:09

Nikunj Patel


I think you can read and watch the content that was made available during IO 2011 by Reito Meier.

Google IO 2011 from Meier (watch video, get slides, get code snippets...):
http://blog.radioactiveyak.com/2011/05/android-protips-where-to-download.html

Reito Meier's publication about Location-based applications:
http://blog.radioactiveyak.com/2011/06/how-to-build-location-based-apps-that.html
http://blog.radioactiveyak.com/2011/06/deep-dive-into-location-part-2-being.html

like image 25
Benoit Duffez Avatar answered Sep 22 '22 02:09

Benoit Duffez