2017-03-08 56 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.prepare()之後添加了Looper.loop(),但沒有任何更改: -/ – DarkWing89

+0

它可能是一個愚蠢的問題,但是你在一分鐘內移動了嗎?如果GPS沒有檢測到位置的任何變化(達到某個閾值應該在幾十釐米左右),即使最小距離等於零,該事件也不會被觸發。除此之外,你能否更新你的代碼以包含你所做的修改? – 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啓用和IM試圖讓位置。如果我使用網絡及GPS提供商都我得到一個錯誤「線程已經運行」 所以我決定先用1個提供商來解決它,並添加第二事後。但onLocationChanged的回調從未完成。 requestOnLocationUpdates與您的相同: - / – DarkWing89