Android 服务函数onLocationChanged()返回异步任务中的0.0坐标

Android 服务函数onLocationChanged()返回异步任务中的0.0坐标,android,location,latitude-longitude,Android,Location,Latitude Longitude,在我的android应用程序中,有一个服务和异步任务。我使用PostData AsyncTask以多种方式向服务器发送数据: 手动方法,主要活动如下: protected void onResume() { // TODO Auto-generated method stub super.onResume(); //10_06_2013 //Останавливаем наш сервис определения координат Intent int

在我的android应用程序中,有一个服务和异步任务。我使用PostData AsyncTask以多种方式向服务器发送数据:

手动方法,主要活动如下:

protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    //10_06_2013
    //Останавливаем наш сервис определения координат
    Intent intentstop = new Intent(this,GPSTracker.class);
    stopService(intentstop);
Toast.makeText(getApplicationContext(), "service STOP", Toast.LENGTH_LONG).show(); //Test
    //Стартуем наш сервис определения координат
    Intent intentstart = new Intent(this,GPSTracker.class);
    startService(intentstart);
Toast.makeText(getApplicationContext(), "service START", Toast.LENGTH_LONG).show(); //Test
    // Gets the user's network preference settings
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    //Здесь берутся из настроек Параметры отвечающие за позиционирования разрешено или нет
    Boolean GPSnotif = sharedPrefs.getBoolean("location_share_enordis", true);
    //проверяем наличие файла если его нет то координаты не отправляются 12_06_2013 //______This block work
    String FILELOGIN = "TeleportSAASUser.txt";
    File filelogin = getBaseContext().getFileStreamPath(FILELOGIN);
    if (filelogin.exists()) {
    //______This block work

    if (GPSnotif.equals(true)) {
        GPSdetermination();
        new PostData(gps, RD, getBaseContext()).execute();
        Toast.makeText(getApplicationContext(), R.string.location_send_toast, Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(getApplicationContext(), R.string.share_location_NO, Toast.LENGTH_LONG).show();
    }
    }
    else {
        Toast.makeText(getApplicationContext(), R.string.check_user_profile_toast, Toast.LENGTH_LONG).show();
    }

}
更改用户在my GPSTracker类中的位置时,自动方法OnLocation已更改

public class GPSTracker extends Service implements LocationListener {
private final Context mContext;

//определяем переменную главного активити
    MainActivity ma;
    GPSTracker gps;
    Teleport_user_profile_activity UP;
    ReadData RD;
    PostData PD;
    Context rdContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 0;; // 0 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public static String UserLoginFile;
public static String UserPassFile;

// Функция для определения местоположения
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}
/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}



//события которые происходят если позиция поменялась
@Override
public void onLocationChanged(Location location) {
    this.location = location;

  //Здесь берутся из настроек Параметры отвечающие за позиционирования разрешено или нет
    SharedPreferences sharedPrefs = mContext.getSharedPreferences("location_share_enordis", Context.MODE_PRIVATE);
    Boolean GPSnotif = sharedPrefs.getBoolean("location_share_enordis", true);

    if (GPSnotif.equals(true)) {
        //Отправка местоположения если позиция изменилась 10_06_2013____This block work
        GPSTracker gps = new GPSTracker(this); // работает
        new PostData(gps, RD, mContext).execute();
        //Test to LogCat
        Log.d("LOCATION CHANGED_IN_GPSTracker_Latitude", location.getLatitude() + "");
        Log.d("LOCATION CHANGED_IN_GPSTracker_Longitude", location.getLongitude() + "");
    } 
    else {

    }


}


@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

@Override
public IBinder onBind(Intent arg0) {
    return null;
}
}

LogCat

06-12 10:01:31.656: D/GPS Enabled(2077): GPS Enabled
06-12 10:01:31.715: D/Start AsyncTask PostData(2077): Started
06-12 10:01:31.715: D/LOCATION_IN_PostData_Latitude(2077): 49.422005000000006
06-12 10:01:31.715: D/LOCATION_IN_PostData_Longitude(2077): -129.08409333333333
06-12 10:01:31.936: I/Choreographer(2077): Skipped 42 frames!  The application may be doing too much work on its main thread.
06-12 10:01:31.945: D/gralloc_goldfish(2077): Emulator without GPU emulation detected.
06-12 10:01:32.495: I/Choreographer(2077): Skipped 33 frames!  The application may be doing too much work on its main thread.
06-12 10:01:33.255: E/Web Console(2077): Viewport argument value "device-width;" for key "width" not recognized. Content ignored. at http://myheart.pp.ua/:8
06-12 10:01:33.255: V/Web Console(2077): Viewport argument value "1.0;" for key "initial-scale" was truncated to its numeric prefix. at http://myheart.pp.ua/:8
06-12 10:01:33.255: V/Web Console(2077): Viewport argument value "1.0;" for key "maximum-scale" was truncated to its numeric prefix. at http://myheart.pp.ua/:8
06-12 10:01:33.275: V/Web Console(2077): Viewport argument value "0;" for key "user-scalable" was truncated to its numeric prefix. at http://myheart.pp.ua/:8
06-12 10:01:34.265: D/dalvikvm(2077): GC_CONCURRENT freed 231K, 4% free 8194K/8519K, paused 30ms+110ms, total 191ms
06-12 10:01:34.985: W/SingleClientConnManager(2077): Invalid use of SingleClientConnManager: connection still allocated.
06-12 10:01:34.985: W/SingleClientConnManager(2077): Make sure to release the connection before allocating another one.
06-12 10:01:50.095: W/System.err(2077): java.lang.NullPointerException
06-12 10:01:50.095: W/System.err(2077):     at android.content.ContextWrapper.getSystemService(ContextWrapper.java:416)
06-12 10:01:50.095: W/System.err(2077):     at com.teleport.saas.GPSTracker.getLocation(GPSTracker.java:70)
06-12 10:01:50.095: W/System.err(2077):     at com.teleport.saas.GPSTracker.<init>(GPSTracker.java:60)
06-12 10:01:50.095: W/System.err(2077):     at com.teleport.saas.GPSTracker.onLocationChanged(GPSTracker.java:214)
06-12 10:01:50.095: W/System.err(2077):     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:237)
06-12 10:01:50.095: W/System.err(2077):     at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:170)
06-12 10:01:50.106: W/System.err(2077):     at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:186)
06-12 10:01:50.106: W/System.err(2077):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-12 10:01:50.106: W/System.err(2077):     at android.os.Looper.loop(Looper.java:137)
06-12 10:01:50.106: W/System.err(2077):     at android.app.ActivityThread.main(ActivityThread.java:4745)
06-12 10:01:50.106: W/System.err(2077):     at java.lang.reflect.Method.invokeNative(Native Method)
06-12 10:01:50.106: W/System.err(2077):     at java.lang.reflect.Method.invoke(Method.java:511)
06-12 10:01:50.106: W/System.err(2077):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-12 10:01:50.106: W/System.err(2077):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-12 10:01:50.106: W/System.err(2077):     at dalvik.system.NativeStart.main(Native Method)
06-12 10:01:50.125: D/LOCATION CHANGED_IN_GPSTracker_Latitude(2077): 11.422005000000002
06-12 10:01:50.125: D/LOCATION CHANGED_IN_GPSTracker_Longitude(2077): -111.084095
06-12 10:01:50.135: D/Start AsyncTask PostData(2077): Started
06-12 10:01:50.135: D/LOCATION_IN_PostData_Latitude(2077): 0.0
06-12 10:01:50.135: D/LOCATION_IN_PostData_Longitude(2077): 0.0
06-12 10:01:50.315: W/SingleClientConnManager(2077): Invalid use of SingleClientConnManager: connection still allocated.
06-12 10:01:50.315: W/SingleClientConnManager(2077): Make sure to release the connection before allocating another one.
但在PostData AsyncTask中,它们为null 0.0

06-12 10:01:50.135: D/LOCATION_IN_PostData_Latitude(2077): 0.0
06-12 10:01:50.135: D/LOCATION_IN_PostData_Longitude(2077): 0.0
我无法理解AsyncTask中的函数接收空0.0纬度和经度的原因。请帮我解决我的问题。我应该对AsyncTask的代码进行哪些更改,通过自动数据发送方法获取正确的纬度和经度值。 提前感谢。

只需使用:

LocationManager loc = (LocationManager) getSystemService(Context.LOCATION_SERVICE)
为了得到服务

然后是LocationListener,后跟实现它的类。like=>

LocationListener listener = new MyLocationListener();
然后通过requestLocationUpdates方法获取更新。like=>

loc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, your minimum time, your minimum distance, listener)
不要忘记创建内部类MyLocationListener,它必须实现LocationListener接口。like=>

public class MyLocationListener implements LocationListener{

    @Override
    public void onLocationChanged(Location location) {
    //**fetch all your latitudes and longitudes through location object**        }

   @Override
    public void onProviderDisabled(String provider) {
    //**do our show something when gps is disabled** 

   }

  @Override
    public void onProviderEnabled(String provider) {

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

  //**Do/Show something when status changed i.e provider is unable to fetch data** 
   }
。。。。。。。。。。 首先添加此代码以启用gps和wifi(如果禁用)

要启用GPS,请执行以下操作:

     String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if (!provider.contains("gps")) {
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");

        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        sendBroadcast(poke);
    }
关于WIFI:

     WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);

      if (!wm.isWifiEnabled()) {
        wm.setWifiEnabled(true);
      } else {
         // for disable when requir
         wm.setWifiEnabled(false);
      }
如果你要以强硬的态度做一件简单的事情,那么它一定会让你感到困惑

祝你一切顺利

     WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);

      if (!wm.isWifiEnabled()) {
        wm.setWifiEnabled(true);
      } else {
         // for disable when requir
         wm.setWifiEnabled(false);
      }