在android中,我使用LocationManager找到手机的位置(经度,纬度),如下:
LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
这应该放在 Activity 中,因为方法 getSystemService
是在 Activity
类中定义的。 (如有错误请指正)。
但我想在没有任何 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();
}
}
}
}
}
我在我的 list 文件中注册我的接收器:
<receiver android:name="com.example.find_me.SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
有没有办法在不使用任何 Activity 的情况下找到手机的位置?如果没有,你能告诉我在我的情况下应该怎么做吗? 再次强调:我想在接收短信时找到手机的位置,我不希望任何 Activity 都在那个时刻运行。
最佳答案
您可以使用 context.getSystemService(Context.LOCATION_SERVICE);
它在您使用 this
关键字的 Activity 中起作用,因为您的 Activity 是一个上下文。
幸运的是,您有一个上下文对象传递给您的 onReceive
,只需使用它即可。
@Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// whatever you need to do
}
关于android - 在没有 Activity 运行时查找手机的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22938942/