anu_r
anu_r

Reputation: 1622

How to track trigger a service using Broadcast receivers when a location is changed in android?

I am developing an app where I am required to put my phone on the silent mode when I reach a particular latitude and longitute. I want this service to run in the background even when the app is not launched. I am using a BroadCastReceiver and a service for this. Can anyone help me out with this? My code is as below:

GPSTracker.java

 public class GPSTracker extends Service implements LocationListener {
 @Override
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();

}
  }

BootUpReceiver.java

public class BootUpReceiver extends BroadcastReceiver{
GPSTracker g;
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    /*Intent i = new Intent(context, GPSTracker.class);
    context.startService(i);*/
    String action = intent.getAction();
    if(action.equals(context.getSystemService(LocationManager.KEY_LOCATION_CHANGED)))
    {
        String key = LocationManager.KEY_LOCATION_CHANGED;
        Location location = (Location)intent.getExtras().get(key);
        if (location != null) {
            g.onLocationChanged(location);
            Intent serviceIntent = new Intent(context,GPSTracker.class);
        }
    }
}

}

Upvotes: 1

Views: 439

Answers (1)

ik024
ik024

Reputation: 3596

Make use of startforeground() in service. This will make the service to run in backdround continuously, refer the below link for help on this Android - implementing startForeground for a service?

Upvotes: 3

Related Questions