Anand Barnwal
Anand Barnwal

Reputation: 313

Start Service from BroadcastReceiver to find gps location

I'm new to android and I'm trying to access gps location when a SMS is received. I'm calling the service like this:

Intent findGPS = new Intent(context, MyService.class);

context.startService(findGPS); 

I'm trying to print a toast in service class so as know whether it has started or not but it doesn't print the toast. Can anyone suggest me how to write service class for location access.

public class MyService extends Service{

........

public void onCreate()

{
    Log.e(TAG, "onCreate");
    Toast.makeText(this,"Its Working !!!", Toast.LENGTH_LONG).show();
    initializeLocationManager();
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[1]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "network provider does not exist, " + ex.getMessage());
    }
    try {
        mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                mLocationListeners[0]);
    } catch (java.lang.SecurityException ex) {
        Log.i(TAG, "fail to request location update, ignore", ex);
    } catch (IllegalArgumentException ex) {
        Log.d(TAG, "gps provider does not exist " + ex.getMessage());
    }
}

}

Upvotes: 0

Views: 231

Answers (1)

Pankaj Arora
Pankaj Arora

Reputation: 10274

service will called automatically when you recieve a broadcast.

public class BReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    
    try {
        // call your service here
          startService(new Intent(getapplicationcontext(),ImageDownloader .class));
    } catch (Exception e) {
        e.printStackTrace();
    }
 }

}

// make a java class and extend it with intent service because it has stop self functionality,because services drains battery when they running in background thats why i suggest you to use intent service,after completing the task it will atop auomatically.

Service class:

public class ImageDownloader extends IntentService {

public ImageDownloader() {
    super("DownLoadImages");
}

@Override
public void onCreate() {
    super.onCreate();
 }

@Override
protected void onHandleIntent(Intent intent) {
   // do your stuff here
   }
} 

Upvotes: 1

Related Questions