2016-03-24 3 views
0

Ich mache eine App, die die Klingeltöne von Benutzern stumm schaltet, wenn sie sich an einem bestimmten Ort befinden. Aus irgendeinem Grund glaube ich nicht, dass die distanceTo() Methode funktioniert. Wenn ich die Entfernung protokolliere, heißt das immer, dass die Orte zwischen 9 Millionen und 10 Millionen Meter entfernt sind. Was mache ich falsch?Verwende ich Location.DistanceTo() korrekt?

  public class MainActivity extends AppCompatActivity implements LocationListener { 
PlacePicker.IntentBuilder builder; 
int PLACE_PICKER_REQUEST; 
ListView placeListView; 
ArrayList<String> placeArrayList; 
ArrayList<String> latitudeArrayList; 
ArrayList<String> longitudeArrayList; 
ArrayAdapter<String> arrayAdapter; 
SharedPreferences sharedPreferences; 
SharedPreferences.Editor editor; 
ArrayList<Double> latitudeList; 
Integer counter; 
LocationManager locationManager; 
String provider; 
double lat; 
double lng; 
Place place; 
static Set<String> set; 
static Set<String> set1; 
static Set<String> set2; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    placeListView = (ListView) findViewById(R.id.placeListView); 
    latitudeList = new ArrayList<>(); 
    placeArrayList = new ArrayList<String>(); 
    latitudeArrayList = new ArrayList<String>(); 
    longitudeArrayList = new ArrayList<String>(); 


    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    provider = locationManager.getBestProvider(new Criteria(), false); 


    ListView listView = (ListView) findViewById(R.id.placeListView); 

    SharedPreferences sharedPreferences = this.getSharedPreferences("bro", Context.MODE_PRIVATE); 

    set = sharedPreferences.getStringSet("names", null); 

    set1 = sharedPreferences.getStringSet("lats", null); 
    set2 = sharedPreferences.getStringSet("lngs", null); 


    placeArrayList.clear(); 
    latitudeArrayList.clear(); 
    longitudeArrayList.clear(); 

    if (set != null) { 

     placeArrayList.addAll(set); 
     latitudeArrayList.addAll(set1); 
     longitudeArrayList.addAll(set2); 

    } else { 

     placeArrayList.add("Hold to delete"); 
     set = new HashSet<String>(); 
     set.addAll(placeArrayList); 
     sharedPreferences.edit().putStringSet("names", set).apply(); 
     latitudeArrayList.add(String.valueOf("66.56083")); 
     set1 = new HashSet<String>(); 
     set1.addAll(latitudeArrayList); 
     sharedPreferences.edit().putStringSet("lats", set1).apply(); 
     longitudeArrayList.add(String.valueOf("39.3232")); 
     set2 = new HashSet<String>(); 
     set2.addAll(longitudeArrayList); 
     sharedPreferences.edit().putStringSet("lngs", set2).apply(); 

    } 




    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, placeArrayList); 

    listView.setAdapter(arrayAdapter); 




    placeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
     @Override 
     public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { 


      new AlertDialog.Builder(MainActivity.this) 
        .setIcon(android.R.drawable.ic_dialog_alert) 
        .setTitle("Are you sure?") 
        .setMessage("Do you want to delete this place?") 
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 


          placeArrayList.remove(position); 

          latitudeArrayList.remove(position); 

          SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("bro", Context.MODE_PRIVATE); 

          if (set == null) { 

           set = new HashSet<String>(); 
           set1 = new HashSet<String>(); 
           set2 = new HashSet<String>(); 

          } else { 

           set.clear(); 
           set1.clear(); 
           set2.clear(); 

          } 


          set.addAll(placeArrayList); 
          set1.addAll(latitudeArrayList); 
          set2.addAll(longitudeArrayList); 
          sharedPreferences.edit().remove("names").apply(); 
          sharedPreferences.edit().remove("lats").apply(); 
          sharedPreferences.edit().remove("lngs").apply(); 
          sharedPreferences.edit().putStringSet("names", set).apply(); 
          sharedPreferences.edit().putStringSet("lats", set1).apply(); 
          sharedPreferences.edit().putStringSet("lngs", set2).apply(); 
          arrayAdapter.notifyDataSetChanged(); 


         } 
        }) 
        .setNegativeButton("No", null) 
        .show(); 


      return false; 
     } 
    }); 


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    Location location = locationManager.getLastKnownLocation(provider); 

    if (location != null) { 


     lat = location.getLatitude(); 

     lng = location.getLongitude(); 


     Toast.makeText(getApplicationContext(), String.valueOf(lat) + String.valueOf(lng), Toast.LENGTH_LONG).show(); 


    } else { 

     Toast.makeText(getApplicationContext(), "Unable to get location", Toast.LENGTH_LONG).show(); 

    } 


    arrayAdapter.notifyDataSetChanged(); 
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      PLACE_PICKER_REQUEST = 1; 
      builder = new PlacePicker.IntentBuilder(); 
      pickPlace(); 


     } 
    }); 


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    location = locationManager.getLastKnownLocation(provider); 

    if (location != null) { 


     lat = location.getLatitude(); 

     lng = location.getLongitude(); 


     if (placeArrayList.size() != 0) { 
      for (int i = 0; i < placeArrayList.size(); i++) { 

       Location destination = new Location(provider); 
       destination.setLatitude(Float.valueOf(latitudeArrayList.get(i))/1e6); 
       destination.setLongitude(Float.valueOf(latitudeArrayList.get(i))/1e6); 


       if (location.distanceTo(destination) <= 1000000) { 


        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 

        audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI); 


       } else { 

        Toast.makeText(getApplicationContext(), "Unable to get location", Toast.LENGTH_LONG).show(); 

       } 

      } 


     } 
    } 
} 



public void pickPlace() { 

    try { 
     startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST); 
    } catch (GooglePlayServicesRepairableException e) { 
     e.printStackTrace(); 
    } catch (GooglePlayServicesNotAvailableException e) { 
     e.printStackTrace(); 
    } 


} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == PLACE_PICKER_REQUEST) { 
     if (resultCode == RESULT_OK) { 
      place = PlacePicker.getPlace(data, this); 
      // String toastMsg = String.format("Place: %s", place.getName()); 
      //Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show(); 


      LatLng latLng = place.getLatLng(); 


      int joe = placeArrayList.size(); 

      placeArrayList.add(String.valueOf(place.getName())); 
      latitudeArrayList.add(String.valueOf(place.getLatLng().latitude)); 
      longitudeArrayList.add(String.valueOf(place.getLatLng().longitude)); 
      arrayAdapter.notifyDataSetChanged(); 


      SharedPreferences sharedPreferences = getSharedPreferences("bro", Context.MODE_PRIVATE); 

      if (set == null) { 

       set = new HashSet<String>(); 
       set1 = new HashSet<String>(); 
       set2 = new HashSet<String>(); 

      } else { 

       set.clear(); 
       set1.clear(); 
       set2.clear(); 

      } 


      arrayAdapter.notifyDataSetChanged(); 
      set.addAll(placeArrayList); 
      set1.addAll(latitudeArrayList); 
      set2.addAll(longitudeArrayList); 
      sharedPreferences.edit().remove("names").apply(); 
      sharedPreferences.edit().remove("lats").apply(); 
      sharedPreferences.edit().remove("lngs").apply(); 
      sharedPreferences.edit().putStringSet("names", set).apply(); 
      sharedPreferences.edit().putStringSet("lats", set1).apply(); 
      sharedPreferences.edit().putStringSet("lngs", set2).apply(); 





     } 

    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onLocationChanged(Location location) { 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    location = locationManager.getLastKnownLocation(provider); 

    if (location != null) { 


     lat = location.getLatitude(); 

     lng = location.getLongitude(); 


     for (int i = placeArrayList.size(); i >= 0; i--) { 


      if (lat >= Float.parseFloat(latitudeArrayList.get(i)) - .005 && 
        lat <= Float.parseFloat(latitudeArrayList.get(i)) + .005 && 
        lng >= Float.parseFloat(longitudeArrayList.get(i)) - .005 && 
        lng <= Float.parseFloat(longitudeArrayList.get(i)) + .005) { 


       AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 

       audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI); 


      } else { 

       Toast.makeText(getApplicationContext(), "Unable to get location", Toast.LENGTH_LONG).show(); 

      } 

     } 


    } 
} 

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

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 


} 
+0

Was enthält 'latitudeArrayList' ?? – newhouse

+0

Auch, was ist 'location'? – CommonsWare

+0

Entschuldigung. Ich habe gerade den Rest meines Codes hinzugefügt. – felix

Antwort

0

Ich denke Wert von Float.valueOf (latitudeArrayList.get (i)) in Millionen zurückgeführt wird. versuchen Sie Float.valueOf(latitudeArrayList.get(i))/1e6

auch bitte placeArrayList zum Inhalt dieser Array-Liste.

+0

Ich habe gerade versucht, es zu teilen meine 1e6 und es hat immer noch nicht funktioniert. Kann ich noch etwas anderes machen? Ich habe gerade den Rest meines Codes hinzugefügt. – felix

+0

Ich denke, das würde das Problem lösen lat = location.getLatitudeE6(); lng = location.getLongitudeE6(); ' – iDevRoids