2017-03-08 1 views
0

클래스 GPSController을 만들었습니다. onReceive는 매분마다 호출됩니다.Android AsyncTask 및 LocationListener

AsyncTaskGPSListener의 현재 GPS 데이터를 가져오고 싶습니다. 그러나 onLocationChanged 메서드는 호출되지 않습니다. : -/

여기 내 클래스입니다 :

public class GPSController extends SensorTimeController { 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 2; 
    private boolean isGPSEnabled = false; 
    private boolean isNetworkEnabled = false; 
    private double latitude = -1; 
    private double longitude = -1; 
    private double altitude = -1; 
    private double speed = 0L; 
    private double bearing = 0L; 
    private LocationManager locationManager; 
    private GPSLocationTask backgroundTask; 

    public GPSController(GPSModule module) { 
     super(module); 
     backgroundTask = new GPSLocationTask(); 
    } 

    private void SensorDataFinished(double longitude, double latitude, double altitude, double speed, double bearing) { 
     Date date = new Date(System.currentTimeMillis()); 
     SensorRecord record = new SensorRecord(module.getNextIndex(), date, structure); 
     if (longitude != -1) 
      record.addData("longitude", String.valueOf(longitude)); 
     else 
      record.addData("longitude", " "); 

     if (latitude != -1) 
      record.addData("latitude", String.valueOf(longitude)); 
     else 
      record.addData("latitude", " "); 

     if (altitude != -1) 
      record.addData("altitude", String.valueOf(altitude)); 
     else 
      record.addData("altitude", " "); 

     if (bearing != 0L) 
      record.addData("bearing", String.valueOf(bearing)); 
     else 
      record.addData("bearing", " "); 

     if (speed != 0L) 
      record.addData("speed", String.valueOf(speed)); 
     else 
      record.addData("speed", " "); 

     module.log(record); 

    } 


    @Override 
    public void onReceive(Context context, Intent intent) { 
     locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     backgroundTask.execute(); 
    } 

    private class GPSLocationTask extends AsyncTask<Void, Void, Void> implements LocationListener { 

     @Override 
     protected Void doInBackground(Void... params) { 
      System.out.println("THREAD STARTED"); 
      try { 
       Looper.prepare(); 
       Looper.loop(); 
       if(isNetworkEnabled) 
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       if(isGPSEnabled) 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
      }catch(SecurityException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 


     public void onLocationChanged(Location location) { 
      if (location != null) { 
       longitude = location.getLongitude(); 
       latitude = location.getLatitude(); 
       altitude = location.getAltitude(); 

       // don't do anything if we get a null reading for some reason 
       if (longitude == 0.0f && latitude == 0.0f) 
        return; 

       // any speed information? 
       if (location.hasSpeed()) 
        speed = (double) location.getSpeed(); 

       // any bearing information? 
       if (location.hasBearing()) 
        bearing = (double) location.getBearing(); 
       System.out.println(longitude+", "+ latitude+", "+ altitude+", "+ speed+", "+ bearing); 
       SensorDataFinished(longitude, latitude, altitude, speed, bearing); 
      } 
     } 

     public void onProviderDisabled(String provider) { 

     } 

     public void onProviderEnabled(String provider) { 

     } 

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

     } 
    } 
} 
+0

내가 잘못 본 것이 아니라면,'''Looper.loop()''' – Anis

+0

을 보내 주셔서 감사합니다! 나는 Looper.loop()를 Looper.prepare() 후에 추가했지만 아무것도 변경하지 않았습니다 : -/ – DarkWing89

+0

그것은 바보 같은 질문으로 올 수 있습니다. GPS가 위치의 변화를 감지하지 못하면 (최소 임계 값은 수십 센티미터가되어야 함) 최소 거리가 0 인 경우에도 해당 이벤트가 실행되지 않을 수 있습니다. 옆에, 당신이 한 수정 사항을 포함하도록 코드를 업데이트 할 수 있습니까? – Anis

답변

0

이 클래스는, 현재의 위도를 제공 로그인 onLocationChanged 방법은 AsyncTask를 모든 분이라고 호출 할 수 있습니다.

public class GPSTracker extends Service implements LocationListener { 

     private static final String TAG = GPSTracker.class.getSimpleName(); 
     private final Context mContext; 

     // flag for GPS status 
     boolean isGPSEnabled = false; 

     // flag for network status 
     boolean isNetworkEnabled = true; 

     // 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 * 1; // 1 minute 

     // Declaring a Location Manager 
     protected LocationManager locationManager; 

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

     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) { 

       } else { 
        if (isGPSEnabled) { 
         if (location == null) { 
          locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          canGetLocation = true; 
          Log.d("GPS Enabled", "GPS Enabled"); 

          if (locationManager != null) { 
           location = locationManager 
             .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
           if (location != null) { 
            latitude = location.getLatitude(); 
            longitude = location.getLongitude(); 
    //        SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude); 
    //        SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude); 
    //        SharedPreferenceUtil.save(); 
    //        Preferences.TAG_G_L = "G"; 
            Log.d("gps", latitude + "," + longitude); 
           } 
          } 
         } else { 
          canGetLocation = false; 
          Log.d("gps", "GPS Disable"); 
         } 
        } 
       } 

       if (!isNetworkEnabled) { 
        // no network provider is enabled 
       } else { 
        if (isNetworkEnabled) { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
    //     Preferences.TAG_G_L = "L"; 
         Log.d("Network", "Network"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
    //       SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude); 
    //       SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude); 
    //       SharedPreferenceUtil.save(); 
           Log.d("network", latitude + "," + longitude); 
          } 
         } 
         Log.d("network", latitude + "," + longitude); 
        } 
       } 



       /* if (!isGPSEnabled && !isNetworkEnabled) { 
        // no network provider is enabled 
       } else { 
        this.canGetLocation = true; 
        // First get location from Network Provider 
        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(); 
           SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude); 
           SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude); 
           SharedPreferenceUtil.save(); 
           Log.d("gps",latitude+","+longitude); 
          } 
         } 
        } 
        // 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(); 
            SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude); 
            SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude); 
            SharedPreferenceUtil.save(); 
            Log.d("gps",latitude+","+longitude); 
           } 
          } 
         } 
        } 
       }*/ 

      } 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 
     * 
     * @return double 
     */ 
     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) { 
      Log.e(TAG, "onLocationChanged: " + location.toString()); 
     } 

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

    } 

나는 당신에게 도움이되기를 바랍니다 ..!

+0

고마워요! 이미 원본 스레드에서이 메서드를 보았습니다. (당신은 몇 가지 동일한 변수를 볼 수 있습니다 - P) 나는 네트워크 및 GPS가 활성화되어 있는지 확인하고 위치를 얻으려고 시도하는 방법을 사용했습니다. NETWORK & GPS Provider를 사용하는 경우 "스레드가 이미 실행 중입니다"라는 메시지가 나타납니다. 그래서 먼저 1 공급자로 해결하고 이후에 두 번째를 추가하기로 결정했습니다. 그러나 onLocationChanged에 대한 콜백은 절대로 수행되지 않습니다. requestOnLocationUpdates는 귀하의 것과 같습니다 : - / – DarkWing89