0

我是 Android 开发的新手。我正在开发一个应用程序,在接收到带有唯一文本字符串的 SMS 消息后,启用 GPS 并开始跟踪手机的位置。我遇到的问题是getSystemService()方法。我收到错误"The method getSystemService(String) is undefined for the type SmsReceiver",我相信这是因为它没有上下文。我试图在我的代码中使用“ctx”添加上下文,这消除了错误,但每次我在手机上运行它时我的应用程序都会崩溃。接收 SMS 的代码工作正常,如果它在我的主类中,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) { }
    }
}
4

1 回答 1

0

您可以将 Context 作为参数传递给enableGPS并使用它来调用getSystemService

于 2010-11-13T20:52:14.853 回答