2013-07-11 4 views
0

GPS에서 위치 정보를 받고지도에 점을 그려주는 간단한 앱을 작성하려고합니다. GPS 처리를위한 서비스를 작성했지만 Activity에서 사용하는 데 문제가 있습니다. 위도/경도/고도 값을 가져올 수 없습니다.GPS 업데이트 용 Android 서비스

서비스가 올바르게 시작된 것처럼 보입니다. (GPS가 전화에서 시작되어 수정본을 가져옵니다.)하지만 관련 메소드를 호출하기 위해 활동에서 버튼을 눌러 좌표를 가져 오려고하면 앱이 다운되고 Java가 발생합니다. LogCat에서 lang.NullPointerException 오류가 발생했습니다.

스택 오버플로 및 다른 웹 사이트에서 많은 예제를 살펴 보았지만 Android 개발을 처음 접했고 잘못된 것을 잘 모릅니다. 나는 모든 조언에 크게 감사 할 것입니다.

서비스 :

public class TrackingService extends Service { 
private LocationManager SgpstLocationManager; 
private LocationListener spgstLocationListener; 

private static long minimumDistanceBwUpdates = 10; //10 metres 
private static long minimumTimeBwUpdates = 3000; //3 seconds 

static Location location; 

private void startTrackingService() { 
    //location manager declaration 
    SgpstLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

    //location listener declaration 
    spgstLocationListener = new SgpstLocationListener(); 

    //request location updates from location manager 
    SgpstLocationManager.requestLocationUpdates(
      SgpstLocationManager.GPS_PROVIDER, 
      minimumTimeBwUpdates, 
      minimumDistanceBwUpdates, 
      spgstLocationListener); 
} 

private void stopTrackingService() { 
    //remove location updates from location manager 
    SgpstLocationManager.removeUpdates(spgstLocationListener); 
} 

//location listener class 
public class SgpstLocationListener implements LocationListener { 
    public void onLocationChanged(Location location) { 
     if (location != null) { 
      try { 
       if (location.hasAccuracy()) { 
        //retrieve information about a point: 
        location.getLatitude(); 
        location.getLongitude(); 
       }     
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    } 

    public void onProviderDisabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onProviderEnabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     //mandatory method - not used 
    } 
} 

//mandatory service methods 
public void onCreate() { 
    super.onCreate(); 
    startTrackingService(); 
} 

public void onDestroy() { 
    super.onDestroy(); 
    stopTrackingService(); 
} 

//methods for interaction with client objects 
private final IBinder sgpstBinder = new LocalBinder(); 

@Override 
public IBinder onBind(Intent intent) { 
    return sgpstBinder; 
} 

public class LocalBinder extends Binder { 
    TrackingService getService() { 
     return TrackingService.this; 
    } 
} 

//get and set methods 
public static void setMinimumDistanceBwUpdates(long distance) { 
    minimumDistanceBwUpdates = distance; 
} 

public static void setMinimumTimeBwUpdates(long time) { 
    minimumTimeBwUpdates = time; 
} 

public static long getMinimumDistanceBwUpdates() { 
    return minimumDistanceBwUpdates; 
} 

public static long getMinimumTimeBwUpdates() { 
    return minimumTimeBwUpdates; 
} 

public static double getMyLatitude() { 
    return location.getAltitude(); 
} 

public static double getMyLongitude() { 
    return location.getLongitude(); 
} 

public static double getMyAltitude() { 
    return location.getAltitude(); 
} 

} 

활동 : 도움을

public class GPSTestActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_gpstest); 

    startService(new Intent(GPSTestActivity.this, TrackingService.class)); 

    Button updateButton = (Button)findViewById(R.id.update_button); 
    final TextView latitudeText = (TextView)findViewById(R.id.latitude); 
    final TextView longitudeText = (TextView)findViewById(R.id.longitude); 
    final TextView altitudeText = (TextView)findViewById(R.id.altitude); 
    latitudeText.setText("latitude"); 
    longitudeText.setText("longitude"); 
    altitudeText.setText("altitude"); 

    updateButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
       latitudeText.setText(String.valueOf(TrackingService.getMyLatitude())); 
       longitudeText.setText(String.valueOf(TrackingService.getMyLongitude())); 
       altitudeText.setText(String.valueOf(TrackingService.getMyAltitude())); 
      } 
    }); 
} 

많은 감사합니다. 귀하의 제안에 따라 코드를 다시 작성/리팩토링했습니다. 이제 다음과 같은 오류가 나타납니다 :

나는 서비스 바인딩에 대해 읽으려고 노력하지만 어떤 조언도 환영 할 것입니다.

개정 코드 :

서비스 :

public class TrackingService extends Service { 
//fields 
private LocationManager SgpstLocationManager; 
private LocationListener spgstLocationListener; 

private static long minimumDistanceBwUpdates = 10; //10 metres 
private static long minimumTimeBwUpdates = 3000; //3 seconds 

static Location myLocation; 

private void startTrackingService() { 
    //location manager declaration 
    SgpstLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

    //location listener declaration 
    spgstLocationListener = new SgpstLocationListener(); 

    //request location updates from location manager 
    SgpstLocationManager.requestLocationUpdates(
      SgpstLocationManager.GPS_PROVIDER, 
      minimumTimeBwUpdates, 
      minimumDistanceBwUpdates, 
      spgstLocationListener); 
} 

private void stopTrackingService() { 
    //remove location updates from location manager 
    SgpstLocationManager.removeUpdates(spgstLocationListener); 
} 

//location listener class 
public class SgpstLocationListener implements LocationListener { 
    public void onLocationChanged(Location location) { 
     if (location != null) { 
      try { 
       if (location.hasAccuracy()) { 
        //retrieve information about a point: 
        myLocation = location; 
       }     
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    } 

    public void onProviderDisabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onProviderEnabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     //mandatory method - not used 
    } 
} 

//mandatory service methods 
public void onCreate() { 
    super.onCreate(); 
    startTrackingService(); 
} 

public void onDestroy() { 
    super.onDestroy(); 
    stopTrackingService(); 
} 

//methods for interaction with client objects 
private final IBinder sgpstBinder = new LocalBinder(); 

@Override 
public IBinder onBind(Intent intent) { 
    return sgpstBinder; 
} 

public class LocalBinder extends Binder { 
    TrackingService getService() { 
     return TrackingService.this; 
    } 
} 

//get and set methods 
public static void setMinimumDistanceBwUpdates(long distance) { 
    minimumDistanceBwUpdates = distance; 
} 

public static void setMinimumTimeBwUpdates(long time) { 
    minimumTimeBwUpdates = time; 
} 

public static long getMinimumDistanceBwUpdates() { 
    return minimumDistanceBwUpdates; 
} 

public static long getMinimumTimeBwUpdates() { 
    return minimumTimeBwUpdates; 
} 

public static double getMyLatitude() { 
    return myLocation.getAltitude(); 
} 

public static double getMyLongitude() { 
    return myLocation.getLongitude(); 
} 

public static double getMyAltitude() { 
    return myLocation.getAltitude(); 
} 

} 

활동

public class GPSTestActivity extends Activity { 

boolean trackingServiceBounded; 
TrackingService trackingService; 
TextView latitudeText = (TextView)findViewById(R.id.latitude); 
TextView longitudeText = (TextView)findViewById(R.id.longitude); 
TextView altitudeText = (TextView)findViewById(R.id.altitude); 
Button updateButton = (Button)findViewById(R.id.update_button); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_gpstest); 

    //startService(new Intent(GPSTestActivity.this, TrackingService.class)); 

    latitudeText.setText("latitude"); 
    longitudeText.setText("longitude"); 
    altitudeText.setText("altitude"); 

    updateButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
       latitudeText.setText(String.valueOf(TrackingService.getMyLatitude())); 
       longitudeText.setText(String.valueOf(TrackingService.getMyLongitude())); 
       altitudeText.setText(String.valueOf(TrackingService.getMyAltitude())); 
      } 
    }); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    Intent intent = new Intent(this, TrackingService.class); 
    bindService(intent, serviceConnection, BIND_AUTO_CREATE); 
} 

//bind Activity to the Service 
ServiceConnection serviceConnection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName name, IBinder service) { 
     trackingServiceBounded = true; 
     LocalBinder localBinder = (LocalBinder)service; 
     trackingService = localBinder.getService(); 
    } 

    public void onServiceDisconnected(ComponentName name) { 
     trackingServiceBounded = false; 
     trackingService = null; 
    } 
}; 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (trackingServiceBounded) { 
     unbindService(serviceConnection); 
     trackingServiceBounded = false; 
    } 
} 

} 

답변

0

location을 선언하지만 절대로 인스턴스화하지 마십시오.
는 청소기 코드가 다른 파일에 SgpstLocationListener 클래스를 이동해야하기 onLocationChange

if (location.hasAccuracy()) { 
        //save location in the private variable: 
        this.location = location; 
       } 
+0

아차, 이해를 바랍니다! 스캇은 이미 대답했다. – ramaral

+0

'이 없습니다.location '은 Service 클래스의 필드가 아닌 Location Listener 클래스의 필드 (onLocationChanged()가 메소드 임)를 참조합니까? 나는 코드를 리팩터링하려고했으나 (아래 참조), 작동하지 않았고 여전히 nullPointerException을 얻고 있었다. – whtvr

+0

네가 맞다. – ramaral

0

에서이 작업을 수행합니다.
더 좋아해서 CurrentLocation의 이름을 myLocation으로 바꿀 것입니다. 당신은 GPS가 작동하는지 확인해야합니다 진행하기 전에 SgpstLocationListener

public static double getMyLatitude() { 

     return spgstLocationListener.myLocation.getLatitude(); 
    } 

에서

서비스 이용에
//location listener class 
public class SgpstLocationListener implements LocationListener { 

    public Location myLocation; //THIS IS WHAT YOU READ IN THE SERVICE 

    public void onLocationChanged(Location location) { 
     if (location != null) { 
      try { 
       if (location.hasAccuracy()) { 
        //retrieve information about a point: 
        myLocation = location; //SET TO THE CURRENT POSITION 
       }     
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    } 

    public void onProviderDisabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onProviderEnabled(String provider) { 
     //mandatory method - not used 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     //mandatory method - not used 
    } 
} 

이 얻을 수있는 위도 !

당신은 이미 내 영어다시피

이 매우 좋지 않다, 나는 당신이