vadimpopov94
@vadimpopov94
Dev

Почему не работает Timer в Thread?

Реализовал отправку координат пользователя на сервер, в UI потоке без TIMER код отрабатывает, теперь пытаюсь запускать поток раз в 5 секунд, ниже листинг
private void refreshUserCoordinates(final Context contextThread) {
    Intent intent = getIntent();
    final String user = intent.getStringExtra("user");
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            GeoPosition geoPosition = new GeoPosition();
            geoPosition.SetUpLocationListener(contextThread);
            ServerInteraction serverInteraction = new ServerInteraction("http://razdvatri/refreshCoordinates.php",
                    "{\"user\" " + ":\"" + user + "\", \"latitude\" " + ":\"" + geoPosition.getLatitude() + "\", \"longitude\" :" + "\"" + geoPosition.getLongitude() + "\"" + "}", "put");
            serverInteraction.execute();
        }
    }, 0L, 50L * 1000);
}

Вот что пишет LogCat

05-17 16:14:06.735 5372-5441/popovvad.findme E/AndroidRuntime: FATAL EXCEPTION: Timer-0 Process: popovvad.findme, PID: 5372 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.(Handler.java:204) at android.os.Handler.(Handler.java:118) at android.location.LocationManager$ListenerTransport$1.(LocationManager.java:234) at android.location.LocationManager$ListenerTransport.(LocationManager.java:234) at android.location.LocationManager.wrapListener(LocationManager.java:872) at android.location.LocationManager.requestLocationUpdates(LocationManager.java:885) at android.location.LocationManager.requestLocationUpdates(LocationManager.java:470) at popovvad.findme.GeoPosition.SetUpLocationListener(GeoPosition.java:49) at popovvad.findme.MapActivity$1.run(MapActivity.java:81) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) 05-17 16:14:30.306 5372-5372/popovvad.findme D/AndroidRuntime: Shutting down VM 05-17 16:14:30.307 5372-5372/popovvad.findme I/Process: Sending signal. PID: 5372 SIG: 9

Понимаю, что основная ошибка описана здесь -

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Как починить ?
  • Вопрос задан
  • 324 просмотра
Решения вопроса 1
vadimpopov94
@vadimpopov94 Автор вопроса
Dev
Помогло в итоге в методе run() добавить
if (Looper.myLooper() == null){
     Looper.prepare();
 }

Полный листинг
private void refreshUserCoordinates(final Context contextThread) {
    Intent intent = getIntent();
    final String user = intent.getStringExtra("user");
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (Looper.myLooper() == null)
            {
                Looper.prepare();
            }
            GeoPosition geoPosition = new GeoPosition();
            geoPosition.SetUpLocationListener(contextThread);
            ServerInteraction serverInteraction = new ServerInteraction("http://razdvatri.ru/refreshCoordinates.php",
                    "{\"user\" " + ":\"" + user + "\", \"latitude\" " + ":\"" + geoPosition.getLatitude() + "\", \"longitude\" :" + "\"" + geoPosition.getLongitude() + "\"" + "}", "put");
            serverInteraction.execute();
        }
    }, 0L, 50L * 1000);
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы