Android,单击按钮时获取GPS位置

时间:2013-07-15 08:54:55

标签: android gps

我正在尝试学习如何在Android中使用GPS服务,为此,我正在开发一个程序,当用户按下按钮时显示实际的GPS位置。

但每当我按下它时,我得到0.0 ......

我认为这段代码不能正常工作:

LocationManager mlocManager=null;
    LocationListener mlocListener;
    mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    mlocListener = new MyLocationListener();
    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(LOGTAG,"onCLickButton");
                firstCoord.setText("");
            Log.d(LOGTAG,Double.toString(MyLocationListener.latitude));
            Log.d(LOGTAG, "AAAAAAAA");
            if(MyLocationListener.latitude>0)
                {
                    coordLat1 = MyLocationListener.latitude;
                    coordLon1 = MyLocationListener.longitude;
                    firstCoord.setText(Double.toString(coordLat1) + ' ' + Double.toString(coordLon1));
                }
                else
                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(home_screen.this);
                    alert.setTitle("Wait");
                    alert.setMessage("GPS en progress, wait.");
                    alert.setPositiveButton("OK", null);
                    alert.show();
                }
        }
    });

onClickbutton之后的第一个日志显示0.0但是如果我使用谷歌地图应用程序,它会显示我的手机所在的位置。我认为这个问题是我没有得到坐标。

这是我的MyLocationListener类:     package com.gps.distance;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class MyLocationListener implements LocationListener {

private static final String LOGTAG = "LogsAndroid";
public static double latitude;
public static double longitude;

@Override
public void onLocationChanged(Location loc)
{
    loc.getLatitude();
    loc.getLongitude();
    latitude=loc.getLatitude();
    longitude=loc.getLongitude();
    Log.d(LOGTAG, "TAKE POS");
}

@Override
public void onProviderDisabled(String provider)
{
    //print "Currently GPS is Disabled";
    Log.d(LOGTAG, "GPS DISABLED");
}
@Override
public void onProviderEnabled(String provider)
{
    //print "GPS got Enabled";
    Log.d(LOGTAG, "GPS ENABLED");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
永远不会使用

onLocationChanged。如果我禁用或启用GPS,则会显示日志,但onLocationChanged不会......从不。

0 个答案:

没有答案