0

LocationListener に onLocationChanged メソッドを起動させるにはどうすればよいですか?

私はこれが初めてです(JavaとAndroid)。これが私がやっていることです。context.startService(serviceIntent); を呼び出して、場所のリクエストを処理します。インテント サービス内には、onHandleIntent メソッドの側で LocationListener として機能するネストされたクラスがあります。ロケーションの更新を要求するスレッドを開始します。LocationListener オブジェクトへの参照と、OnHandleIntent メソッドのトレッドを維持します。

私の計画は、onLocationChanged メソッドで変数を更新して、更新が完了したかどうかを定期的に確認し、ループから抜け出して場所を操作することでした。

問題は、onLocationChanged メソッドが呼び出されないことです。LocationListener オブジェクトは、onHandleIntent メソッドの最後まで有効です。直接呼び出して、期待するデバッグ メッセージを取得することもできます。DDMS が場所を変更していることは確かです。さまざまなデバッグ ログに出力したところ、場所が変更されていることがわかります。

コードは次のとおりです。

package com.example.locationrequestreceiver;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;

public class LocationRequestService extends IntentService    {


    private LocationManager locationManager;

    public class UpdateHandler implements Runnable, LocationListener {

        @Override
        public void onLocationChanged(Location arg0) {
            Log.d("myStuff", "inside location changed");
        }

        @Override
        public void onProviderEnabled(String provider) {}
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Looper.prepare();
            Log.d("myStuff", "inside thread");
            locationManager.requestLocationUpdates("gps", 0, 0, this);
            Log.d("myStuff", "run ending");
            Looper.loop()  //  <--- this was the fix
        }

    }

    public LocationRequestService() {
        super("LocationRequrestService");
        Log.d("myStuff", "inside the service");
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        UpdateHandler update_handler = new UpdateHandler();
        Thread update_handler_thread = new Thread(update_handler);
        Log.d("myStuff", "starting thread");
        update_handler_thread.start();

        for (int count = 0; count < 20; count++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
        Location location = locationManager.getLastKnownLocation("gps");
        update_handler.onLocationChanged(location);
    }




}
4

1 に答える 1

0

呼び出しスレッドにはLooperが必要です。Thread の代わりにHandlerThreadを使用できます。

于 2013-07-23T22:18:56.757 に答える