1

Android用の私のアプリケーションでは、サービスとasynctaskがあります。PostData AsyncTask を使用して、いくつかの方法でデータをサーバーに送信します。

  1. 次の構成による 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();
        }
    
    }
    
  2. 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;
    }
    

    }

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 が示すように正しく送信されます。しかし、自動メソッドの座標を更新する必要があるとすぐに、それらは関数 onLocationChanged() に分類されます

LOCATION CHANGED_IN_GPSTracker_Latitude(2077): 11.422005000000002
LOCATION CHANGED_IN_GPSTracker_Longitude(2077): -111.084095

しかし、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 の関数が null (0.0) の緯度と経度を受け取る理由がわかりません。私の問題を解決するのを手伝ってください。AsyncTask のコードにどのような変更を加える必要があるかは、自動データ送信メソッドによって正しい緯度と経度の値を取得しました。前もって感謝します。

4

1 に答える 1

0

単に使用するだけです:

LocationManager loc = (LocationManager) getSystemService(Context.LOCATION_SERVICE)

サービスを受けるために。

それから LocationListener の後に it.like => を実装するクラスが続きます

LocationListener listener = new MyLocationListener();

次に、requestLocationUpdates メソッドを使用して更新をフェッチします。いいね=>

loc.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, your minimum time, your minimum distance, listener)

LocationListener インターフェイスを実装する必要がある内部クラス MyLocationListener を作成することを忘れないでください。

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 と Wi-Fi が無効になっている場合に有効にします。

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);
      }

簡単なことを難しいやり方で行うと、混乱するに違いありません。

ではごきげんよう

于 2013-08-15T09:47:18.397 に答える