Forum Xamarin.Android

How do I fix the error "Can't create handler inside thread that has not called Looper.prepare()"

RonWhiteRonWhite USMember ✭✭

I have spent a few days trying to solve this. Found lots of answers most were to old to even apply or were all about RunOnUiThread. I don't even have a UI in this case. I have an ILocationListener that runs as a foreground service. I have a sub procedure that starts a new thread like this:

    ThreadPool.QueueUserWorkItem(tok =>
                while (!token.IsCancellationRequested)
                    //at the end of each loop, I set the update rate like this.
                    locMgr.RequestLocationUpdates(locationProvider, LocTime, 20, this);

That thread runs forever(hopefully). Sometimes I want the Location listener to check location every 10 seconds. Sometimes I want it to check every minute. This actually works great on my phone and most devices that I have tested on. But some devices refuse to listen to my suggestion to check every minute and they run constantly. This kills the battery pretty fast. If I move that RequestLocationUpdates any where else inside that ThreadPool, I get the Looper error. I really don't understand why it works at the end of that while statement and no where else, but it does. So I decided that I will just turn the Location listener on when I want it and off when I don't. I turn it off in the OnLocationChanged event with this:


If I do that, I can't turn it back on. The RequestLocationUpdates line in the code above gets the Looper error.

"Java.Lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()"

I think I get why this is happening, but I don't know how to fix it. When the service thread stops updating the location the worker thread doesn't have access to the main thread to turn it back on? Any ideas?


  • MihaMarkicMihaMarkic SI ✭✭✭✭

    Why are you doing that on a separate thread in first place?
    I mean you could listen for changes, set parameters, etc. on main thread, and if you do something lengthy when location changes then do it on separate thread.

  • RonWhiteRonWhite USMember ✭✭

    Thanks for th reply. Good question. This is my first app and the sample code that I based my app on had this code running on the main activity. I realized that I needed my app to run as a service. So I just moved the main activity code to the service. So you are correct, I probably don't need that thread.

    I did get everything to work though. I just created a new service to run the location services. Then my service that has that worker thread just starts and stops the location thread as needed. This works very well.

    Now I am going to look into removing that thread.

Sign In or Register to comment.