我是Android开发的新手。我正在开发一个应用程序,在收到带有唯一文本字符串的SMS消息后,启用GPS并开始跟踪手机的位置。我遇到的问题是使用getSystemService()
方法。
我收到错误"The method getSystemService(String) is undefined for the type SmsReceiver"
,我相信这是因为它没有上下文。我试图在我的代码中使用'ctx'添加上下文,这样就消除了错误,但每次我在手机上运行它时我的应用程序崩溃了。接收短信的代码工作正常,如果在我的主要班级,GPS位置跟踪代码工作正常。
我仍然不完全理解背景,有人可以帮助我吗?
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
@SuppressWarnings("deprecation")
public class SmsReceiver extends BroadcastReceiver {
LocationManager lm;
LocationListener loc;
Context ctx;
public SmsReceiver(Context c) { ctx = c; }
@Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null){
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getMessageBody().toString() + "\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
if (msgs[0].getMessageBody().toString() == "Track"){
enableGPS();
}
}
}
public void enableGPS() {
lm = (LocationManager)ctx.getSystemService(Context.LOCATION_SERVICE);
loc = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc);
}
public void disableGPS() {
lm.removeUpdates(loc);
}
private class mylocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
String s = "";
s += "\tTime: " + location.getTime() + "\n";
s += "\tLatitude: " + location.getLatitude() + "°\n";
s += "\tLongitude: " + location.getLongitude() + "°\n";
s += "\tAccuracy: " + location.getAccuracy() + " metres\n";
s += "\tAltitude: " + location.getAltitude() + " metres\n";
//Toast.makeText(SmsReceiver.this, s, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String arg0) { }
@Override
public void onProviderEnabled(String arg0) { }
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) { }
}
}
答案 0 :(得分:0)
您可以将Context作为参数传递给enableGPS
并使用它来调用getSystemService