簡體   English   中英

Android我的位置 - 修復

[英]Android My Location-Fix

當我的地圖活動被調用時,我在onCreate中調用addUserMapPoint。 此函數包含兩個實例,我嘗試使用myOverlay.getMyLocation獲取位置信息。 在此活動的初始加載時,第一次嘗試的結果返回一個空的GeoPoint,並在主UI線程完成位於myOverlay.runOnFirstFix的監聽器線程中的第二次嘗試(新的Runnable()...在一秒后調用並且確實包含一個包含lat和lon的GeoPoint。這個監聽器函數內的調用看起來似乎把點放在地圖上,而mapController.animateTo(gp)行確實將地圖移動到我的位置。我的應用程序有一個刷新按鈕,當clicked再次觸發此活動。我需要lat和lon才能從另一個服務獲取位置數據。刷新后,第二次通過map活動代碼我期待第一次調用myOverlay.getMyLocation()現在將是能夠獲得GeoPoint,但它仍然是null。

如果我不能通過第一次調用myOverlay.getMyLocation來獲取GeoPoint,那么如何從myOverlay.runOnFirstFix(new Runnable()...線程中找到的第二個調用中傳遞lat和lon值。你會注意到我一直在嘗試將lat和lon添加到MyApp,這是輔助bean類,但是即使在刷新之后,此類中的lat和lon也為null。如果我在addUserMapPoint函數中手動設置lat和lon第一次活動訪問這些值是保留的。我猜這是因為它是在主UI線程上設置的。

public class MapActivity extends com.google.android.maps.MapActivity {
    private MapView mapView = null;
    private MapController mapController = null;
    private MyLocationOverlay myOverlay = null;

    public static MyApp app;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        app = (MyApp) getApplicationContext();

        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();

        List<Overlay> mapOverlays = mapView.getOverlays();
        mapOverlays.clear();

        addUserMapPoint(mapView);

        if (!app.isLocServOff()) {
            //map other points – service call to get items from our service near lat and lon
            addOtherMapPoints(mapOverlays);

        } else {
            Toast.makeText(app.getApplicationContext(),"Current location could not be found.",Toast.LENGTH_LONG).show();
        }

    }

    private void addUserMapPoint(MapView mapView){
            myOverlay = new MyLocationOverlay(app.getApplicationContext(), mapView);
            myOverlay.disableCompass();
        myOverlay.enableMyLocation();


            if(app.getMyLat()==null||app.getMyLon()==null){
                GeoPoint gp = myOverlay.getMyLocation();
                if(gp!=null){
                    app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                    app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                    app.setLocServOff(false);
                }else{
                    app.setLocServOff(true);
                }
        }


        myOverlay.runOnFirstFix(new Runnable() {   
                public void run() {     
                    GeoPoint gp = myOverlay.getMyLocation();    
                    if(gp!=null){
                        app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                        app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                        app.setLocServOff(false);   
                        mapController.animateTo(gp);
                    }else{
                        app.setLocServOff(true);
                    }
                }    
            });

        mapView.getOverlays().add(myOverlay);
    }   

}

我們要求您提供以下問題的幫助。 如何在主UI線程中獲得包含lat和lon的GeoPoint,或者如何從GeoPoint傳遞這些值,我可以從myOverlay.runOnFirstFix(new Runnable()...線程獲取?

如果您打算建議我使用Handler或runOnUiThread,請提供代碼示例,將lat和lon傳遞回主UI線程/地圖視圖可以使用的內容。 我嘗試過以下代碼,但沒有產生預期的結果。 我能夠得到吐司的消息,但是無法以我可以使用的方式傳遞lat和lon。

    final Handler handler = new Handler();   
    myOverlay.runOnFirstFix(new Runnable() {                     
        @Override public void run() {

            handler.post(new Runnable() {                                   
                @Override public void run() {

                        GeoPoint gp = myOverlay.getMyLocation();    
                        if(gp!=null){
                            app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                            app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                            app.setLocServOff(false);   
                            mapController.animateTo(gp);                                

                        }else{
                            app.setLocServOff(true);
                        }

                    //Toast.makeText(getApplicationContext(),"wowoowowowoowoowowow",Toast.LENGTH_LONG).show();                      
                    }                                  
                });

            }                
        }); 

我也使用了以下代碼來獲取lat和lon並且它可以工作,但是因為當前位置有時會比whas被返回不同的lat和lang因為我無法獲得gps信號但是舊的價值被退回。 我添加了檢查以查看lat / lon數據是否超過2分鍾,但我仍然無法將最新的lat和lon與myOverlay.getMyLocation返回的相匹配。

    LocationManager locMgr = (LocationManager)appcontext.getSystemService(Context.LOCATION_SERVICE);
    MyLocationListener locLstnr = new MyLocationListener();

    //fetch current location for current location 
    locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locLstnr, appcontext.getMainLooper());  

你可以找到一些關於如何在UI線程中獲取當前位置的示例,但首先是一些背景信息。

在請求新位置后, GPS可能需要一些時間(15秒到1分鍾)才能獲得第一次修復。 這是您第一次嘗試從myOverlay獲取它失敗的原因,並且只有在第一次修復后才能獲得該值。

在此停電期間,如果您趕時間,可以使用getLastKnownLocation()獲取最后一個知名的GPS位置。 如果不可用,則返回null

編碼:

最后一個位置

LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null){
    //we have a valid location. Check location date
}

請求單個位置更新

LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, appcontext.getMainLooper);

請求連續位置更新

LocationManager locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//use 0 for minDistance and minDistance between updates if you need the maximum update frequency.
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minDistance, minTime, locationListener);

單點和連續位置更新的位置監聽器

這是最后一段代碼,也是您獲得上述新位置的地方。

當通過GPS檢索到與上面定義的請求匹配的新位置時,將立即調用此偵聽器,除非您的設備忙於執行其他無法中斷的操作(即回調位於暫停的線程或鎖定時) 。

onLocationChanged()您可以根據需要設置任何類級別。 如果您從UI線程注冊了偵聽器,那么它將在UI上運行。

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location fix) {
        fix.setTime(fix.getTime() + timeZoneOffset); //Add Timezone offset if needed
        //here you have a fresh new location in fix...
        //You can set the value of any class level field from here
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};

問候。

在尋找Device的位置時,您必須考慮的一些最重要的要點是:

  1. 無法保證在足夠的時間內收到衛星GPS定位。 例如,設備位於建築物內/不在開闊的天空下。
  2. 確保衛星GPS聽眾不會長時間保持活動狀態。 保持聆聽器開啟意味着始終保持GPS無線電一直是電池消耗最大的原因。

在下面的代碼示例中,LinkedBlockingQueue中的poll方法在指定的時間間隔結束或Location排隊之前不會返回。

使用以下內容獲取當前位置:

    Location getCurrentLocation() {
    long startmillis = 0;
    LinkedBlockingQueue<Location> mQueue = new LinkedBlockingQueue<Location>();
            try{


                long millisSinceLastCollection = System.currentTimeMillis() - startmillis; 


                startmillis = System.currentTimeMillis();
                mQueue.clear();

    // Register for Satellite GPS listener as well as Network GPS listener.
                registerGPSListeners();

                // Wait for a maximum of one minutes for a fix
                Location firstfix = mQueue.poll(1, TimeUnit.MINUTES);


                if(firstfix != null && firstfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    return firstfix;
                }

                long elapsedmillis = System.currentTimeMillis() - startmillis;
                long remainingmillis = ONE_MINUTE_IN_MS - elapsedmillis; 
                if (remainingmillis <= 0){
                    return firstfix;
                }

                Location secondfix = mQueue.poll(remainingmillis, TimeUnit.MILLISECONDS);

                if(secondfix != null && secondfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    return secondfix;
                }

                /*
                 * In case we receive fix only from Network provider, return it.
                 */
                if(firstfix != null && firstfix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
                    return firstfix;
                }

            } catch(Exception e){
                Logger.e("GPS: Exception while listening for the current location", e);
            } finally {
                Logger.i("GPS: Unsubscribing from any existing GPS listeners");
                unregisterGPSListeners();

            }
    }


// GPS issue fix edit.
    private void registerGPSListeners() {

        LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);

        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, oneShotNetworkGPSLocationListener, MyAppApp.getAppContext().getMainLooper());

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100, oneShotSatelliteGPSLocationListener, AirWatchApp.getAppContext().getMainLooper());
        }
    }

    private void unregisterGPSListeners(){

        final LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
        locationManager.removeUpdates(oneShotSatelliteGPSLocationListener);
        locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
    }

//One shot location listener
    protected LocationListener oneShotSatelliteGPSLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            try {
                mQueue.put(location);
            } catch (InterruptedException e) {
                Logger.e("Exception in putting new Location to the queue", e);
            }

            Logger.d("GPS: Location received from Satellite GPS Provider");
            unregisterGPSListeners();
        }

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

    //One shot location listener
    protected LocationListener oneShotNetworkGPSLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            try {
                mQueue.put(location);
            } catch (InterruptedException e) {
                Logger.e("Exception in putting new Location to the queue", e);
            }

            Logger.d("GPS: Location received from Network GPS Provider");
            // Stop Listener for one-shot location fix from Network GPS provider.
            final LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
            locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
            Logger.d("GPS: Unsubscribed the network location listener.");
        }

        public void onProviderDisabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
    };
handler.post(new Runnable() {                                   
            @Override public void run() {

                    GeoPoint gp = myOverlay.getMyLocation();    
                    if(gp!=null){
                        app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                        app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                        app.setLocServOff(false);

                        // HERE WE HAVE VALID gp VALUE AND WE NEED TO SHARE IT

                        mapController.animateTo(gp);                                

                    }else{
                        app.setLocServOff(true);
                    }
                }                                  
            });

我認為您的app.set / get | MyLat / Lon無法正常工作,因為您從不同的線程調用它們。 要修復它同步set和獲取MyLat / Long的方法。 (創建用於同步和同步的對象)

或者,如果你喜歡處理程序的方式,這應該工作:

final Handler handler = new Handler(); // BE SURE TO RUN THIS LINE ON UI THREAD
...   
myOverlay.runOnFirstFix(new Runnable() {                     
    @Override public void run() {

        // THIS PART WORKS AS BEFORE
        final GeoPoint gp = myOverlay.getMyLocation();
        mapController.animateTo(gp);                        
        ...
        // AND THIS RUNNABLE TO UPDATE MyLat/MyLong FROM UI THREAD
        handler.post(new Runnable() {                                   
            @Override public void run() {
               app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
               app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
            });

        }                
    }); 

Android修改用戶界面並處理來自單個用戶界面線程(主線程)的輸入事件。

如果程序員不使用任何並發結構,則Android應用程序的所有代碼都在此線程中運行。

GPS是確定用戶位置的最佳方式,但過多地ping全球定位衛星會很快耗盡移動設備的電池,花費很長時間來獲取用戶位置,這種方法並不總是在室內工作。 You are not getting your location in first attempt that's why you are getting null over there.

Android的Network Location Provider根據手機信號塔和Wi-Fi信號計算出用戶的位置。 它不僅使用比GPS更少的電池電量,而且它也更快,無論用戶是在室外還是室內,它都能正常工作。

我將下面的工作代碼顯示progress dialog ,聽取用戶的位置,並在獲取位置后顯示用戶的location overlayGoogle地圖上

我假設你在Menifest file給出了以下權限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
我的主要課程

public class MyLocationOnMap extends MapActivity {

private MapView mapView;
private MyLocationOverlay itemizedoverlay;
private LocationManager locationManager;
private String provider;
private MyLocationListener locationListener;
MyBroadCastreceiver myBroadCastreceiver;
/**
 * My current Location <i>longitude</i>.
 */
static int longitude;
/**
 * My current Location <i>latitude</i>.
 */
static int latitude;
/**
 *My progress indicator. 
 */
ProgressDialog loadingDialog;

public static final String INTENT_FILTER_TAG="my location broadcast receiver";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_location_on_map);

    loadingDialog = new ProgressDialog(this);
    loadingDialog.setTitle("Hot Spots!");
    loadingDialog.setMessage("Please wait ...");
    loadingDialog.setIndeterminate(true);
    loadingDialog.setCancelable(false);

    loadingDialog.show();

 // Configure the Map
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setStreetView(true);

    /**
     * Get your location manager and Location Listener...
     */
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationListener=new MyLocationListener();

    myBroadCastreceiver = new MyBroadCastreceiver();

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Log.i("GPS_Enabled", "GPS enable! listening for gps location.");
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
            registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Log.i("Network_Enabled", "Network enable! listening for Network location.");
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener);
            registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
        } else {
            loadingDialog.dismiss();
            Toast.makeText(this, "No Provider enable!", Toast.LENGTH_LONG).show();
        }

}//End of onCreate......

 /**
 * My BroadCast Receiver, that is called when i get the location of user.
 * @author Rupesh Yadav.
 *
 */
class MyBroadCastreceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        //Remove location update when you get user`s location very first time.
        locationManager.removeUpdates(locationListener);
        //Remove the broadcast listener that update my location on map.
        unregisterReceiver(myBroadCastreceiver);

        GeoPoint point = new GeoPoint(latitude, longitude);
        mapView.getController().animateTo(point);

        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = MyLocationOnMap.this.getResources().getDrawable(R.drawable.hs_mapoverlay);
        itemizedoverlay = new MyLocationOverlay(drawable, MyLocationOnMap.this);

        OverlayItem overlayitem = new OverlayItem(point, "Hello!", "My Current Location :)");

        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);

        loadingDialog.dismiss();

    }

}

/**
 * My Location listener...
 */
class MyLocationListener implements LocationListener{
    @Override
    public void onLocationChanged(Location location) {
        latitude=(int) ((location.getLatitude())*1E6);
        longitude=(int) ((location.getLongitude())*1E6);

        //Send broadcast to update my location.
        Intent sendLocationIntent=new Intent(INTENT_FILTER_TAG);
        sendBroadcast(sendLocationIntent);
    }
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

}

MyLocationOverlay類

public class MyLocationOverlay extends ItemizedOverlay<OverlayItem> {

Context mContext;
private ArrayList<OverlayItem> hsOverlays = new ArrayList<OverlayItem>();

public MyLocationOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

public MyLocationOverlay(Drawable defaultMarker, Context context) {
    super(boundCenterBottom(defaultMarker));
    mContext = context;
}

@Override
protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return hsOverlays.get(i);
}

@Override
public int size() {
    // TODO Auto-generated method stub
    return hsOverlays.size();
}

/**
 * add new OverlayItem objects to map OverlayItem ArrayList.
 * 
 * @param overlay
 */
public void addOverlay(OverlayItem overlay) {
    hsOverlays.add(overlay);
    populate();
}

/**
 * Called when user clicks on map overlay.
 */
@Override
protected boolean onTap(int index) {
    // TODO Auto-generated method stub
    // return super.onTap(index);
    OverlayItem item = hsOverlays.get(index);
    AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
    dialog.setTitle(item.getTitle());
    dialog.setMessage(item.getSnippet());
    dialog.show();
    return true;
}

您可以根據需要修改Location ListenerBroadcasr Receiver 我希望這能解決你的問題。
最好的祝福!

我用這個類來檢測我的lat&lon:希望這對你也很有用。

示例如何使用: GPSUtility.getInstance(Context).getLatitude(); GPSUtility.getInstance(CamPhotoModeAct.this).getLongitude()

public class GPSUtility {
    public static final String TAG = "GPSUtility";

    private Context ctx;

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    private double latitude;
    private double longitude;

    private static SharedPreferences SHARED_PREF;
    private static SharedPreferences.Editor EDITOR_SHARED_PREF;

    private static GPSUtility this_instance;

    public GPSUtility(Context ctx){
        this.ctx = ctx;
        SHARED_PREF = ctx.getSharedPreferences(ConstantsG.SHARED_PREF_FILE, Context.MODE_PRIVATE);
        EDITOR_SHARED_PREF = SHARED_PREF.edit();
        this.getLocation(innerLocationResult);
    }

    public static GPSUtility getInstance(Context ctx){
        if(this_instance == null)
            this_instance = new GPSUtility(ctx);
        return this_instance;
    }

    public static void updateLocation(Context ctx){
        GPSUtility.getInstance(ctx);//this writes the latitude and longitude in sharable preference file
    }

    public double getLatitude(){
        String latitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LATITUDE,null);
        if(latitudeStr == null){
            latitude = 0.0;
        }
        else{
            latitude = Double.parseDouble(latitudeStr);
        }
        return latitude;
    }

    public double getLongitude(){
        String longitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LONGITUDE,null);
        if(longitudeStr == null){
            longitude = 0.0;
        }
        else{
            longitude = Double.parseDouble(longitudeStr);
        }
        return longitude;
    }

    private void updateWithNewLocation(Location location) {

        if (location != null) {
            latitude = location.getLatitude();
            EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LATITUDE, String.valueOf(latitude) );

            longitude = location.getLongitude();
            EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LONGITUDE, String.valueOf(longitude));

            EDITOR_SHARED_PREF.commit();
        }
    }

    public boolean getLocation(LocationResult result)
    {
        //I use LocationResult callback class to pass location value from GPSUtility to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
        }

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled){
            Toast.makeText(this.ctx, "You should enable gps or be connected to network.", Toast.LENGTH_LONG).show();
            return false;
        }

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();


        timer1.schedule(new GetLastLocation(), 10000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            //Context context = getClass().getgetApplicationContext();
             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }


    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }

    LocationResult innerLocationResult = new LocationResult() {
        @Override
        public void gotLocation(Location location) {
            updateWithNewLocation(location);
        }
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM