2010-11-13 82 views
0

我是Android開發新手。我正在開發一款應用程序,該應用程序在接收到帶有唯一字符串文本的短信時,將啓用GPS並開始跟蹤手機的位置。我遇到的問題是getSystemService()方法。 我收到錯誤"The method getSystemService(String) is undefined for the type SmsReceiver",我相信這是因爲它沒有上下文。我試圖在我的代碼中使用'ctx'添加上下文,並且刪除了錯誤,但每當我在手機上運行它時,我的應用程序都會崩潰。接收SMS的代碼工作正常,如果GPS位置跟蹤代碼位於我的主類中,則該位置跟蹤代碼可以正常工作。方法未定義類型SmsReciever - 內容

我還沒有完全理解上下文,任何人都可以幫我解決嗎?

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

你如何創建'SmsReceiver'的實例?此外,請格式化您的帖子 – Asahi 2010-11-13 20:17:55

回答

0

你可以通過上下文作爲參數傳遞給enableGPS,並用它來調用getSystemService

+0

當然,是從onReceive方法傳遞'上下文'工作。謝謝你的幫助 – bobby123 2010-11-22 03:20:40

相關問題