2011-10-11 26 views
0

我在這裏有一個問題,我不能得到它的工作... 我想獲得最新的GPS位置,但我得到的是空指針異常。 它適用於第一類GPSActivity,但不適用於第二個SmsReceiver。Android locationManager空指針異常? (如何通過上下文?)

我讀到這可能是因爲我必須將上下文傳遞給第二類,但我不知道如何......請幫助!

這裏談到的代碼:

GPSActivity.class

import android.app.Activity; 
import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Toast; 

public class GPSActivity extends Activity { 
    long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters 
    long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in Milliseconds 

    LocationManager locationManager; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    locationManager = 
     (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    locationManager.getAllProviders(); 
    locationManager.requestLocationUpdates(
      LocationManager.GPS_PROVIDER, 
      MINIMUM_TIME_BETWEEN_UPDATES, 
      MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
      new MyLocationListener()); 

    }  

    public void showCurrentLocation() { 
    Location location = 
     locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (location != null) { 
     String message = String.format(
       "Current Location \n Longitude: %1$s \n Latitude: %2$s", 
       location.getLongitude(), location.getLatitude()); 
     Toast.makeText(GPSActivity.this, message, 
       Toast.LENGTH_LONG).show(); 
    } 
    } 
} 

(我扯下了代碼位)

現在,我可以打電話showCurrentLocation並showes我長和緯度值。

我怎麼能做到這一點的位置:

SmsReceive.class(收到短信時,發送的GPS座標)

import ... 
public class SmsReceiver extends BroadcastReceiver 
{ 


    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
    GPSActivity myGPS; 
    myGPS = new GPSActivity(); 

    //---get the SMS message passed in--- 
    Bundle bundle = intent.getExtras();   
    SmsMessage[] msgs = null; 
    if (bundle != null) { 
     //HERE I GET THE NULL POINTER EXCEPTION 
     Location loc = 
     myGPS.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     double varLong = loc.getLongitude(); 
     double varLat = loc.getLatitude(); 
     String locationData = "LONG: " + varLong+ " LAT: " + varLat; 
     Toast.makeText(context, locationData, Toast.LENGTH_SHORT).show(); 
    } 
    } 
} 

的感謝!

回答

2

聲明中smsReceiver類新的LocationManager,並使用以下行

mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
0

創建延伸服務的一類,並進入該實現GPS的任務,因爲在活動將停止/暫停/銷燬你無法獲得每一次。服務將進入後臺,您可以隨時獲得GPS座標,並將位置對象定義爲公共靜態,以便您可以在任何地方將其用於應用程序。