Android Program that Accepts the User Location and Runs in the Background and Notifies the User when they are Within 1 km of that Location

Here is source code of the Program to demonstrate a Program that Accepts a Location from the User, Run in the Background, and Notifies the User when he/she is within 1Km from that Location in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Main Activity

package com.example.mc_question2;
 
import java.util.Calendar;
 
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener {
    Intent loc_intent;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start = (Button) findViewById(R.id.start);
        start.setOnClickListener(this);
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        EditText lat_dest = (EditText) findViewById(R.id.dest_latitude);
        EditText lon_dest = (EditText) findViewById(R.id.dest_lon);
 
        String lat = lat_dest.getText().toString();
        String lon = lon_dest.getText().toString();
        this.loc_intent = new Intent(getBaseContext(), Getlocation.class);
        switch (v.getId()) {
 
        case R.id.start:
            Log.i("in start", "str");
 
                Log.i("Tag", lat);
                Log.i("Tag", lon);
 
                this.loc_intent.putExtra("lat", Double.parseDouble(lat));
                this.loc_intent.putExtra("lon", Double.parseDouble(lon));
 
                startService(this.loc_intent);
            break;
        default:
            break;
        }
    }
 
}

Get Location

package com.example.mc_question2;
 
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
 
public class Getlocation extends Service implements LocationListener {
 
    private Context Context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    int flag = 0;// notifier var
    Location location;
    Notification notification;
    Location mylocation = new Location("");
    Location dest_location = new Location("");
    float distance;
    NotificationManager notifier;
    double latitude;
    double longitude;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 40;// 40 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2;
 
    // update location within a time period of 2 minutes
 
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i("Tag", "on create");
    }
 
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i("Indestroy", "destroyed");
        flag = 0;
        stopSelf();
        stopUsingGPS();
        super.onDestroy();
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        // TODO Auto-generated method stub
        Context = this;
        Log.i("tag", "on start");
        mylocation = getLocation(Context);
 
        Double msg = mylocation.getLatitude();
        Log.i("my long", msg.toString());
 
        Double dest_lat = intent.getDoubleExtra("lat", 0.0);
        Double dest_lon = intent.getDoubleExtra("lon", 0.0);
        Log.i("get lat", dest_lat.toString());
        Log.i("get lon", dest_lon.toString());
 
        this.dest_location.setLatitude(dest_lat);
        this.dest_location.setLongitude(dest_lon);
        Log.i("get lon", dest_lon.toString());
 
        return START_NOT_STICKY;
    }
 
    protected LocationManager locationManager;
 
    public Location getLocation(Context Context) {
 
        try {
            locationManager = (LocationManager) Context
                    .getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
                Log.i("No gps and No Network ",
                        "No gps and No Network is enabled enable either one of them");
                Toast.makeText(this, "Enable either Network or GPS",
                        Toast.LENGTH_LONG).show();
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                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();
        }
 
        return location;
    }
 
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(Getlocation.this);
        }
    }
 
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }
 
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }
 
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
 
    @Override
    public void onLocationChanged(Location location) {
 
        mylocation = getLocation(Context);
        Log.i("Tag", "location changed");
        distance = mylocation.distanceTo(dest_location);
        Log.i("Tag", "" + distance);
        if (flag == 0) {
            if ((distance / 1000) < 1) {
                Log.i("Distance", "dist. b/w < 1km");
                Log.d("location", "" + distance);
                NotificationManager notificationManager = (NotificationManager) Context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        Context, 1, new Intent(Context, MainActivity.class), 0);
                Notification notification = new Notification(
                        R.drawable.ic_launcher,
                        "You are within 1 km from ur destination!!",
                        System.currentTimeMillis());
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.setLatestEventInfo(Context,
                        "You are within 1 km from ur destination!!", "You are "
                                + distance + " meters "
                                + " away from your point of interest ",
                        pendingIntent);
 
                notificationManager.notify(11, notification);
                Vibrator vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
 
                vi.vibrate(1000);
                flag = 1;
                onDestroy();
            }
        }
    }
 
    @Override
    public void onProviderDisabled(String provider) {
    }
 
    @Override
    public void onProviderEnabled(String provider) {
    }
 
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
 
}

Activity_Main

advertisement
advertisement
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="28dp"
        android:text="Enter Destination Latitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/dest_latitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="18dp"
        android:ems="10"
        android:inputType="numberDecimal" >
 
        <requestFocus />
    </EditText>
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/dest_latitude"
        android:layout_below="@+id/dest_latitude"
        android:layout_marginTop="34dp"
        android:text="Enter Destination Longitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
    <EditText
        android:id="@+id/dest_lon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignRight="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:ems="10"
        android:inputType="numberDecimal" />
 
    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/dest_lon"
        android:layout_alignRight="@+id/dest_lon"
        android:layout_below="@+id/dest_lon"
        android:layout_marginTop="29dp"
        android:text="Start" />
 
 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/end"
        android:layout_below="@+id/start"
        android:layout_marginTop="24dp"
        android:textColor="@android:color/darker_gray"
        android:text="Start Again Once reached within 1km of the Destination Point" />
 
</RelativeLayout>

Screenshot_2013-11-16-20-37-02

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.