在我的android应用程序中,有一个服务和asynctask。我使用 PostData AsyncTask 以多种方式向服务器发送数据:
通过以下构造使用 MainActivity 的手动方法:
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(); } }
更改我的 GPSTracker 类中的用户位置时的自动方法 onLocationChanged
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; }
}
日志猫
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 所示。但是一旦需要自动更新坐标的方法,就落入函数onLocationChanged()
LOCATION CHANGED_IN_GPSTracker_Latitude(2077): 11.422005000000002
LOCATION CHANGED_IN_GPSTracker_Longitude(2077): -111.084095
但它们在 PostData AsyncTask 中为空(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 代码进行哪些更改,通过自动数据发送方法获取正确的纬度和经度值。提前致谢。