2015-09-25 1 views
0

Je pensais que ce serait super facile - mais cela prend waaaay plus longtemps qu'il ne le devrait. J'essaye simplement d'obtenir les coordonnées GPS pour aller au logcat, c'est littéralement ça.Obtenir le GPS lorsque Android Intent est lancé

L'intention se déclenche correctement. Le message "Intent Fired" apparaît à chaque fois. L'application refuse simplement d'aller à l'événement changé d'emplacement.

Si quelqu'un pouvait jeter un coup d'œil et me dire où j'échoue, ce serait super apprécié.

public class MyReceiver extends IntentService implements LocationListener { 
private LocationManager locationManager; 
public MyReceiver() { 
    super("MyReceiver"); 
} 

protected void onHandleIntent(Intent intent) { 
    Log.i("DebugMe", "Intent Fired"); 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 
} 
public void onLocationChanged(Location location) { 
    String lat = String.valueOf(location.getLatitude()); 
    String lon = String.valueOf(location.getLongitude()); 
    Log.i("DebugMe", lat + " " + lon); 
    locationManager.removeUpdates(this); 
} 
public void onProviderDisabled(String provider) { 
    Log.d("DebugMe ", "Disabled"); 
} 
public void onProviderEnabled(String provider) { 
    Log.d("DebugMe","Enabled"); 
} 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    Log.d("DebugMe","Status"); 
} 
} 

Merci

Répondre

2

Eh bien, le manager emplacement fonctionne de manière asynchrone et IntentService est mis en œuvre de telle sorte que, lorsque onHandleIntent(Intent intent) retours, le service s'arrête. Cela signifie qu'il est détruit avant que tout emplacement puisse être fourni à votre méthode onLocationChanged(location location). Si vous souhaitez utiliser IntentService, vous devez bloquer la méthode onHandleIntent(Intent intent) pour revenir avant d'avoir votre emplacement, ou utiliser un Service standard et exécuter stopSelf lorsque vous obtenez un objet Location. Gardez à l'esprit que cette implémentation ne s'exécutera pas dans un thread distinct par défaut, comme le ferait un IntentService.

+0

"utiliser un service standard et exécuter stopSelf lorsque vous obtenez un objet Location." - À mon humble avis, c'est la meilleure approche. – CommonsWare

+0

C'est certainement – maciekjanusz

+0

Eh bien, dieu, j'ai demandé - je ne l'aurais jamais compris par moi-même. La raison pour laquelle Im utilisant un service d'intention est parce que cette application doit être capable de prendre des commandes d'adb et cette solution me permet de faire "adb shell am startservice ..." à partir d'un ordinateur portable ... Existe-t-il une autre façon de Recherche GPS de la ligne adb cmd? – Nefariis

0

Vous pouvez utiliser cette classe.

public class GPSTracker extends Service implements LocationListener { 

    private final Context mContext; 

    // 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 
    double altitude; // altitude 
    public boolean isLocationAlertShown = true; 
    public boolean comeBackAfterTurnGPSON = false; 


    // 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 && !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; 
    } 
    public void Bearing(Location start,Location end) 
    { 
     start.bearingTo(end); 
    } 

    /** 
    * 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 get altitude 
    * */ 
    public double getAltitude(){ 
     if(location != null){ 
      altitude = location.getAltitude(); 
     } 

     // return latitude 
     return altitude; 
    } 
    /** 
    * 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); 
     alertDialog.setCancelable(true); 

     // Setting Dialog Title 
     //  alertDialog. 

     // Setting Dialog Message 
     alertDialog.setMessage("Please Turn on Location Services"); 

     // 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); 
       comeBackAfterTurnGPSON = true; 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     EventBus.getDefault().post(new OnLocationChange(location)); 
    } 

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

}