android - 在没有 Activity 运行时查找手机的位置

标签 android gps android-activity sms broadcastreceiver

在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
}

Context.getSystemService() documentation

关于android - 在没有 Activity 运行时查找手机的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22938942/

相关文章:

java - 如何使用字符串中的类名启动新的 android Activity ?

android - 从偏好 Activity 启动 Activity

android - 无法实例化类 android.support.v7.widget.SearchView

javascript - 如何在 Android 上为谷歌地图使用 RouteBoxer.js

android - 从数据库中读取一个值

mysql - 对于 GPS 坐标,我应该在数据库中存储多少位有效数字?

android - RxJava2 如何在请求参数更改时更新现有订阅

java - 获取照片的 gps 位置

objective-c - 如何在iOS中存储GPS坐标?

Android Studio Activity Java 文件无法识别 XML