Question

In android, I find the location (Longitude, Latitude) of the phone using the LocationManager, as the following:

LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

This should be placed in an Activity because the method getSystemService is defined in the Activity class. (Please correct me if I am wrong).

But I want to find the location of the phone without having any activity running. I want to find the location of the phone on the receiving of an SMS message. Here's my SMSReceiver class which extends BroadcastReceiver

public class SMSReceiver extends BroadcastReceiver {

  private String message;


@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();

SmsMessage[] msgs = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
if (msgs.length >= 0) {
msgs[0] = SmsMessage.createFromPdu((byte[]) pdus[0]);
message = msgs[0].getMessageBody().toString();


//if it's the locating command
if(message.equals("find location xyz"))
{
    PhoneLocater pl = new PhoneLocater();
    pl.locatePhone();
}


else
{Toast.makeText(context,"Nothing",Toast.LENGTH_LONG ).show();
}


}
}
}
}

I register my receiver in my manifest file:

<receiver android:name="com.example.find_me.SMSReceiver"> 
<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>

Is there a way to find the location of the phone without using any activity? If not, can you please advise what I should do in my case? Again: I want to find the location of the phone on the receiving of SMS, and I don't want any activity to be necessarily running at that moment.

Was it helpful?

Solution

You can use context.getSystemService(Context.LOCATION_SERVICE);

It works in your activity with the this keyword because your activity is a context.

Luckily you have a context object passed to your onReceive, just use that.

@Override
public void onReceive(Context context, Intent intent) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    // whatever you need to do
}

Context.getSystemService() documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top