在我的android應用程序中有一個服務和一個asynctask。我用POSTDATA的AsyncTask將數據發送到服務器在幾個方面:被以下建設MainActivity服務函數onLocationChanged()在AsyncTask中返回0.0座標
手冊方法:改變是在用戶的位置時
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(); } }
自動的方法OnLocationChanged我GPSTracker類
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.
當使用發送座標到服務器的手動方法。座標是通過函數gps.getLatitude(); gps.getLongitude();並按照LogCat所示正確發送。 但只要需要更新自動方式的座標,他們在POSTDATA的AsyncTask
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
分爲()onLocationChanged功能
LOCATION CHANGED_IN_GPSTracker_Latitude(2077): 11.422005000000002
LOCATION CHANGED_IN_GPSTracker_Longitude(2077): -111.084095
,但他們都爲空(0.0),我可以不明白爲什麼AsyncTask中的函數收到null(0.0)經度和緯度的原因。請幫我解決我的問題。我應該通過自動數據發送方法對我的AsyncTask代碼進行哪些更改,以獲取正確的緯度和經度值。 在此先感謝。