Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import android.location.Location;
import android.location.LocationManager;

public class Main {
    /**
     * This method returns the last,best known current location for user
     * @param context
     * @return
     */
    public static Location getLastBestLocation(Context context) {

        // get location providers
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location locationNet = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        // check which ones are available
        boolean haveGPS = (locationGPS != null);
        boolean haveNet = (locationNet != null);

        if (!haveGPS && !haveNet) { // no providers available
            String msg = "Could not find a location. Using random location now.";
            displayAlert(context, msg);
            Location l = new Location("yum fake location");
            l.setLatitude(45.0);
            l.setLongitude(45.0);
            // uh oh... no location
            return new Location(l);

        } else if (haveGPS && !haveNet) { // only gps available

            return locationGPS;

        } else if (!haveGPS && haveNet) { // only cell location available

            return locationNet;

        } else { // choose the most recent one

            long GPSLocationTime = locationGPS.getTime();
            long NetLocationTime = locationNet.getTime();

            if (GPSLocationTime - NetLocationTime > 0) {

                return locationGPS;

            } else {

                return locationNet;

            }
        }

    }

    /**
     * This method shows an alert box with specified message
     * @param context
     * @param message
     */
    public static void displayAlert(final Context context, String message) {

        AlertDialog.Builder alert = new AlertDialog.Builder(context);

        alert.setTitle("Yumm! Alert:");
        alert.setMessage(message);
        alert.setCancelable(false);
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        });
        alert.show();
    }
}