【发布时间】:2014-04-08 13:43:58
【问题描述】:
在android中,我使用LocationManager找到手机的位置(经度,纬度),如下:
LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
这应该放在一个 Activity 中,因为 getSystemService 方法是在 Activity 类中定义的。 (如果我错了,请纠正我)。
但我想在没有任何活动运行的情况下找到手机的位置。我想在收到短信时找到手机的位置。这是我的 SMSReceiver 类,它扩展了 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();
}
}
}
}
}
我在清单文件中注册了我的接收器:
<receiver android:name="com.example.find_me.SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
有没有办法在不使用任何活动的情况下找到手机的位置?如果没有,你能告诉我在我的情况下应该怎么做吗? 再说一遍:我想在收到短信时找到手机的位置,并且我不希望在那一刻有任何活动必须运行。
【问题讨论】:
-
context.getSystemService 将在 SMS 接收器中工作
-
我从哪里获得上下文?我说我没有正在运行的活动。
-
onReceive向您传递上下文。看看你得到的参数。它是第一个参数。 -
噢噢噢!这是正确的。我会尝试并回复您。
标签: android gps android-activity sms broadcastreceiver