GPS not working in Async Task

前端 未结 3 401
北海茫月
北海茫月 2021-01-25 03:05

I have implemented a simple GPS program that fetches the co-ordinates and displays them on the screen. When I tried to improve on this design and implement an async task, the GP

3条回答
  •  滥情空心
    2021-01-25 03:34

    You can't do that. The thread dies as soon as doInBackground() returns. The GPS listener is a Handler which requires a Looper thread to operate. At the beginning of doInBackground() you need to call Looper.prepare() then at the end call Looper.loop(). It will loop forever until you call quit() on the thread's Looper object.

    AsyncTask is really designed for one-shot temporary threads though, so I'd use a normal thread for this. Although, there's no reason you couldn't I suppose. You just have to make 100% sure that you end the loop or it will run forever even after the user closes the app.

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

提交回复
热议问题