Using GPS on Android (Java)

Class for retrieving gps location on android programming.
This source will try to get minimum 4 satellite, if can't get 4 satellite, that's will read last known location. To call this class u can using the code below in your activity:
 public LocationResult locationResult = new LocationResult(){  
     @Override  
     public void gotLocation(final Location location){  
       //Got the location!  
          Glat = location.getLatitude();  
          Glong = location.getLongitude();  
     }  
 }  

To call the function code on top you can using this:
 //declare the class MyLocation first on your activity  
 private MyLocation myLocation = new MyLocation();   
 //call the code location results  
 myLocation.init(this, locationResult);  

Class MyLocation:
 class MyLocation{  
   /**  
    * If GPS is enabled.   
    * Use minimal connected satellites count.  
    */  
   private static final int min_gps_sat_count = 5;  
   /**  
    * Iteration step time.  
    */  
   private static final int iteration_timeout_step = 500;  
   LocationResult locationResult;  
   private Location bestLocation = null;  
   private Handler handler = new Handler();  
   private LocationManager myLocationManager;   
   public Context context;  
   private boolean gps_enabled = false;  
   private int counts  = 0;  
   private int sat_count = 0;  
   private Runnable showTime = new Runnable() {  
      public void run() {  
       boolean stop = false;  
       counts++;  
       //if timeout (1 min) exceeded, stop tying  
       if(counts > 120){  
         stop = true;  
       }  
       //update last best location  
       bestLocation = getLocation(context);  
       //if location is not ready or don`t exists, try again  
       if(bestLocation == null){  
         handler.postDelayed(this, iteration_timeout_step);  
       }else{  
         //if best location is known, calculate if we need to continue to look for better location  
         //if gps is enabled and min satellites count has not been connected or min check count is smaller then 4 (2 sec)   
         if(stop == false && !needToStop()){  
           handler.postDelayed(this, iteration_timeout_step);  
         }else{  
           // removing all updates and listeners  
           myLocationManager.removeUpdates(gpsLocationListener);  
           myLocationManager.removeUpdates(networkLocationListener);    
           myLocationManager.removeGpsStatusListener(gpsStatusListener);  
           sat_count = 0;  
           // send best location to locationResult  
           locationResult.gotLocation(bestLocation);  
         }  
       }  
      }  
   };  
   /**  
    * Determine if continue to try to find best location  
    */  
   private Boolean needToStop(){  
     if(gps_enabled){  
       if(counts <= 4){  
         return false;  
       }  
       if(sat_count < min_gps_sat_count){  
         //if 20-25 sec and 3 satellites found then stop  
         if(counts >= 40 && sat_count >= 3){  
           return true;  
         }  
         return false;  
       }  
     }  
     return true;  
   }  
   //use for stopping retrieving location   
   public void StopLoading(){  
        myLocationManager.removeUpdates(gpsLocationListener);  
     myLocationManager.removeUpdates(networkLocationListener);    
     myLocationManager.removeGpsStatusListener(gpsStatusListener);  
     handler.removeCallbacks(showTime);  
   }  
   /**  
    * Best location abstract result class  
    */  
   public static abstract class LocationResult{  
      public abstract void gotLocation(Location location);  
    }  
   /**  
    * Initialize starting values and starting best location listeners  
    *   
    * @param Context ctx  
    * @param LocationResult result  
    */  
   public void init(Context ctx, LocationResult result){  
     context = ctx;  
     locationResult = result;  
     myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
     gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);  
     bestLocation = null;  
     counts = 0;  
     // turning on location updates  
     myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);  
     myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);  
     myLocationManager.addGpsStatusListener(gpsStatusListener);  
     // starting best location finder loop  
     handler.postDelayed(showTime, iteration_timeout_step);  
   }  
   /**  
    * GpsStatus listener. OnChainged counts connected satellites count.  
    */  
   public final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {  
     public void onGpsStatusChanged(int event) {  
        if(event == GpsStatus.GPS_EVENT_SATELLITE_STATUS){  
         try {  
           // Check number of satellites in list to determine fix state  
            GpsStatus status = myLocationManager.getGpsStatus(null);  
            Iterable<GpsSatellite>satellites = status.getSatellites();  
            sat_count = 0;  
            Iterator<GpsSatellite>satI = satellites.iterator();  
            while(satI.hasNext()) {  
              GpsSatellite satellite = satI.next();  
              Log.i("GPS Location","Satellite: snr=" + satellite.getSnr() + ", elevation=" + satellite.getElevation());               
              sat_count++;  
            }  
         } catch (Exception e) {  
           e.printStackTrace();  
           sat_count = min_gps_sat_count + 1;  
         }  
        }  
      }  
   };  
   /**  
    * Gps location listener.  
    */  
   public final LocationListener gpsLocationListener = new LocationListener(){  
     public void onLocationChanged(Location location){  
     }  
      public void onProviderDisabled(String provider){}  
      public void onProviderEnabled(String provider){}  
      public void onStatusChanged(String provider, int status, Bundle extras){}  
   };   
   /**  
    * Network location listener.  
    */  
   public final LocationListener networkLocationListener = new LocationListener(){  
     public void onLocationChanged(Location location){  
     }  
      public void onProviderDisabled(String provider){}  
      public void onProviderEnabled(String provider){}  
      public void onStatusChanged(String provider, int status, Bundle extras){}  
   };   
   /**  
    * Returns best location using LocationManager.getBestProvider()  
    *   
    * @param context  
    * @return Location|null  
    */  
   public static Location getLocation(Context context){  
     // fetch last known location and update it  
     try {  
       LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
       Criteria criteria = new Criteria();  
       criteria.setAccuracy(Criteria.ACCURACY_FINE);  
        criteria.setAltitudeRequired(false);  
        criteria.setBearingRequired(false);  
        criteria.setCostAllowed(true);  
        String strLocationProvider = lm.getBestProvider(criteria, true);  
        Location location = lm.getLastKnownLocation(strLocationProvider);  
        if(location != null){  
         return location;  
        }  
        return null;  
     } catch (Exception e) {  
       e.printStackTrace();  
       return null;  
     }  
   }  
 }  

Using MapView on Android Application

In this tutorial, I'll try to explain how to use  google map on android application using Google Map API's V1.
First you must get an API Key at http://code.google.com/android/maps-api-signup.html before you debugging your application. You must enter your md5 debug.key, you can search on Google how to get md5 API Key.

first you must add some code to your application manifest. That's code will give your application permission to access google maps.

 //permission to get access for internet and location  
 <uses-permission android:name="android.permission.INTERNET"/>  
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
 <application>  
 . . . . . . . .  
 <uses-library android:name="com.google.android.maps" />  
 . . . . . . . .   
 </application>  

After you've been add that's code to your application manifest, now you can add to your application layout. Like the code bellow:
           <com.google.android.maps.MapView   
          android:id="@+id/mapView"  
          android:layout_width="290dp"  
          android:layout_height="180dp"           
          android:enabled="true"  
          android:clickable="true"  
          android:layout_gravity="center"  
          android:apiKey="YOUR API KEY PUT HERE" />  

Let's cook the code on your java activity. I'm using GPS to get the location using MyLocation class that's I've been write before. Check my another blog post on Using GPS Satellite.
Declare some variable that's its will be used on mapview.


 public class TodoAddActivity extends MapActivity {  
      MapView mapView;   
      MapController mc;  
   GeoPoint p;  

Code for set MapView. In this code I assume that's you've a Latitude and Longitude value.
      public LocationResult locationResult = new LocationResult(){  
     @Override  
     public void gotLocation(final Location location){  
       //Got the location!  
          Glat = location.getLatitude();  
          Glon = location.getLongitude();  
          mGps.setText(location.getLongitude() + " : " + location.getLatitude());    
          mGps.setEnabled(false);  
          mapView.setVisibility(View.VISIBLE);  
             retrieveLocationButton.setEnabled(true);  
             addnewBtn.setEnabled(true);  
             gpsStatus = true;  
       mapView.invalidate();  
       mc = mapView.getController();  
       p = new GeoPoint(  
         (int) (Glat * 1E6),   
         (int) (Glon * 1E6));  
       mc.animateTo(p);  
       mc.setZoom(17);   
       MapOverlay mapOverlay = new MapOverlay();  
       List<Overlay> listOfOverlays = mapView.getOverlays();  
       listOfOverlays.clear();  
       listOfOverlays.add(mapOverlay);  
       mapView.invalidate();   
       };  
     };  
   class MapOverlay extends com.google.android.maps.Overlay  
   {  
     @Override  
     public boolean draw(Canvas canvas, MapView mapView,   
     boolean shadow, long when)   
     {  
       super.draw(canvas, mapView, shadow);            
       //---translate the GeoPoint to screen pixels---  
       Point screenPts = new Point();  
       mapView.getProjection().toPixels(p, screenPts);  
       //---add the marker---  
       Bitmap bmp = BitmapFactory.decodeResource(  
         getResources(), R.drawable.marker);        
       canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);       
       return true;  
     }  
   }   

There is a Class call MapOverlay. it's use to add marker on your map view. if U don't want an Marker on your map, forget that's class :D. just use that's code, you also can customize your zoom level on mc.setZoom([your value])
     mapView.invalidate();   
     mc = mapView.getController();   
     p = new GeoPoint(   
      (int) (Glat * 1E6),    
      (int) (Glon * 1E6));   
     mc.animateTo(p);   
     mc.setZoom(17);  
Okay. See you in another Android Tutorial.