My application crashes when accessing a location service within a method which is called within a Thread. I pass the context from within a service in which the thread is running but it doesn't work.
This is the call to the LocationService
within the thread which is created inside a service.
class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread thread = new Thread(){
@Override
public void run() {
try{
geofix = new GeoFixer(getApplicationContext());
geofix.startLocationObserver();
...
}catch (....){}....
The constructor of GeoFixer
takes the context and saves it in Context context
.
Now inside the method startLocationObserver()
I call getSystemService
with this context which crashes the application.
public class GeoFixer {
...
private Context context;
GeoFixer(Context context){
this.context = context;
}
public void startLocationObserver(){
LocationManager locationManager = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
// This is where it crashes
... }
What am I doing wrong?
EDIT: Here's the LogCat now.
ERROR/AndroidRuntime(8824): FATAL EXCEPTION: Thread-10
ERROR/AndroidRuntime(8824): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
ERROR/AndroidRuntime(8824): at android.os.Handler.<init>(Handler.java:121)
ERROR/AndroidRuntime(8824): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:173)
ERROR/AndroidRuntime(8824): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:173)
ERROR/AndroidRuntime(8824): at android.location.LocationManager._requestLocationUpdates(LocationManager.java:579)
ERROR/AndroidRuntime(8824): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)
ERROR/AndroidRuntime(8824): at de.theapplication.GeoFixer.getNetworkLocation(GeoFixer.java:64)
ERROR/AndroidRuntime(8824): at de.theapplication.GeoFixer.startLocationObserver(GeoFixer.java:27)
ERROR/AndroidRuntime(8824): at de.theapplication.Fadenzieher$1.run(Fadenzieher.java:36)