2016-04-02 3 views
0

public class MapScreen erweitert FragmentActivity implementiert GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener, LocationNun habe ich versucht, andere Lösung den aktuellen Standort eines Benutzers zu erhalten, aber scheiterte

{

final int RQS_GooglePlayServices = 1; 
GoogleMap mymap; 
boolean markerClicked; 
Marker marker; 
LatLng latLng; 

@Override 
public void onBackPressed() { 
    startActivity(new Intent(getApplicationContext(), AfterSignUp.class)); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_map_screen); 
    initializeMap(); 


    /*//Getting Google Play availability status 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 

// Status angezeigt if (Status! = ConnectionResult.SUCCESS) {// Google Play-Dienste nicht verfügbar sind

 int requestCode = 10; 
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
     dialog.show(); 

    }else {*/ // Google Play Services are available 


    FragmentManager myfragmentManager = getFragmentManager(); 
    MapFragment mymapFragment = (MapFragment) myfragmentManager.findFragmentById(R.id.fragment); 

    //Getting reference to the SupportMapFragment of activity main 
    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment); 

    // Getting a reference to the map 
    mymap =mymapFragment.getMap(); 
    //mymap = fm.getMap(); 
    //Enabling my location 
    mymap.setMyLocationEnabled(true); 
    // Getting LocationManager object from System Service LOCATION_SERVICE 
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    // Creating a criteria object to retrieve provider 
    Criteria criteria = new Criteria(); 
    // Getting the name of the best provider 
    String provider = locationManager.getBestProvider(criteria, true); 
    // Getting Current 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 location = locationManager.getLastKnownLocation(provider); 
    if (location != null) { 
     onLocationChanged(location); 
    } 
    locationManager.requestLocationUpdates(provider, 20000, 0, this); 
     /* 
     mypos=new LatLng(latitude,longitude); 
     CameraUpdate cameraUpdate=CameraUpdateFactory.newLatLngZoom(mypos,20); 
     mymap.animateCamera(cameraUpdate);*/ 


    mymap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
    mymap.setOnMapClickListener(this); 
    mymap.setOnMarkerClickListener(this); 
    mymap.setOnMapLongClickListener(this); 
    mymap.setOnInfoWindowClickListener(this); 
    markerClicked = false; 
    mymap.getUiSettings().setMyLocationButtonEnabled(true); 

    MainDbAdapter mainDbAdapter = new MainDbAdapter(getApplicationContext()); 
    Cursor location_cursor = mainDbAdapter.showLocations(); 

    while (location_cursor.moveToNext()) { 
     String lati = location_cursor.getString(location_cursor.getColumnIndex(MainDbAdapter.DbAdapter.Lat)); 
     String longi = location_cursor.getString(location_cursor.getColumnIndex(MainDbAdapter.DbAdapter.Lon)); 
     double lat = Double.parseDouble(lati); 
     double lon = Double.parseDouble(longi); 
     latLng = new LatLng(lat, lon); 
     mymap.addMarker(new MarkerOptions().position(latLng).title("Click to add ")).showInfoWindow(); 

    } 
} 
private void initializeMap() 
{ 
    if(mymap==null) 
    { 
    mymap=((MapFragment)getFragmentManager().findFragmentById(R.id.fragment)).getMap(); 
     if(mymap==null) 
     { 
      Toast.makeText(getApplicationContext(), 
        "Sorry! unable to create maps", Toast.LENGTH_SHORT) 
        .show(); 
     } 
    } 
} 


@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_map_screen, 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 onMapClick(LatLng victoria) { 
    mymap.animateCamera(CameraUpdateFactory.newLatLng(victoria)); 
    markerClicked = false; 
} 


@Override 
public void onMapLongClick(LatLng latLng) { 


    mymap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { 
     @Override 
     public void onMapLongClick(LatLng latLng) { 

      String lat = String.valueOf(latLng.latitude); 
      String lon = String.valueOf(latLng.longitude); 

      marker = mymap.addMarker(new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)).visible(true).title("Click to Edit")); 
      MainDbAdapter mainDbAdapter = new MainDbAdapter(getApplicationContext()); 
      long loc = mainDbAdapter.storeLocations(lat, lon); 
      if (loc > 0) { 
       Toast.makeText(getApplicationContext(), "Location Saved", Toast.LENGTH_SHORT).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), "Location Save failed", Toast.LENGTH_LONG).show(); 
      } 
      Intent intent = new Intent(getApplicationContext(), AfterInfoClick.class); 
      intent.putExtra("lat", lat); 
      intent.putExtra("lon", lon); 
      startActivity(intent); 
     } 
    }); 

} 


@Override 
public boolean onMarkerClick(Marker marker) { 

    marker.showInfoWindow(); 
    return true; 
} 


@Override 
public void onInfoWindowClick(Marker marker) { 
    mymap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { 
     @Override 
     public void onInfoWindowClick(Marker marker) { 

      LatLng latLng1 = marker.getPosition(); 
      String lat = String.valueOf(latLng1.latitude); 
      String lon = String.valueOf(latLng1.longitude); 
      Intent intent = new Intent(getApplicationContext(), OnInfoClick.class); 
      intent.putExtra("lat1", lat); 
      intent.putExtra("lon1", lon); 
      startActivity(intent); 



     } 
    }); 

} 

@Override 
public void onLocationChanged(Location location) { 

    double latitude=location.getLatitude(); 
    double longitude=location.getLongitude(); 
    LatLng mypos=new LatLng(latitude,longitude); 
    //Showing current location in google map 
    mymap.moveCamera(CameraUpdateFactory.newLatLng(mypos)); 
    //Zoom in the google Map 
    mymap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
} 

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

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

}

+0

Was ist der Fehler? –

+0

Verwenden Sie 'criteria.setAccuracy (Criteria.ACCURACY_FINE);' –

Antwort

0

Erstens ist es kein guter Ansatz den gesamten Code in onCreate einer Aktivität zu schreiben. Erstellen Sie stattdessen neue Klassen und schreiben Sie alle Ihre Funktionen mit und rufen Sie sie einfach nach Ihren Bedürfnissen auf.

Zweitens, ich weiß nicht, welche verschiedenen Lösungen Sie bisher versucht haben. Ich poste einen separaten Beispieldienst, der den Benutzerstandort im Hintergrund aktualisiert.

import android.Manifest; 
import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GoogleApiAvailability; 

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 

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

// Declaring a Location Manager 
protected LocationManager locationManager; 

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

public Location getLocation() { 
    try { 
     if (checkPlayServices()) { 
      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 
       if (!isGPSEnabled) { 
        showSettingsAlert(); 
       } else if (!isNetworkEnabled) { 
        UIHelper.showShortToastInCenter(mContext, mContext.getResources().getString(R.string.error_location)); // Unable to get your current location. Please check your internet connection 
       } 
      } else { 
       this.canGetLocation = true; 
       if (!checkFineLocationPermission() && !checkCoarseLocationPermission()) { 
        openNotification(); 
        location = new Location(""); 
        location.setLatitude(0.0d); 
        location.setLongitude(0.0d); 
        return location; 
       } 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        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); 
         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 show settings alert dialog On pressing Settings button will 
* launch Settings Options 
*/ 
public void showSettingsAlert() { 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting DialogHelp Title 
    alertDialog.setTitle(mContext.getResources().getString(R.string.gps_settings)); // GPS settings 

    // Setting DialogHelp Message 
    alertDialog.setMessage(mContext.getResources().getString(R.string.gps_settings_text)); // GPS is not enabled. Do you want to go to settings menu? 

    // On pressing Settings button 
    alertDialog.setPositiveButton(mContext.getResources().getString(R.string.open_settings), new DialogInterface.OnClickListener() { // Open Settings 
     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(mContext.getResources().getString(R.string.dismiss), new DialogInterface.OnClickListener() { // Dismiss 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 

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

@Override 
public void onLocationChanged(Location location) { 
    locationManager.removeUpdates(this); 
} 

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

private boolean checkCoarseLocationPermission() { 
    int result = mContext.checkCallingOrSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION); 
    return result == PackageManager.PERMISSION_GRANTED; 
} 

private boolean checkFineLocationPermission() { 
    int result = mContext.checkCallingOrSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION); 
    return result == PackageManager.PERMISSION_GRANTED; 
} 

private void openNotification() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 
    builder.setIcon(android.R.drawable.ic_dialog_alert) 
      .setTitle(mContext.getResources().getString(R.string.location_permission)) // Location Permissions 
      .setMessage(mContext.getResources().getString(R.string.location_permission_text)) // Please allow this application to use "Location" in order to fetch your current location 
      .setCancelable(false) 
      .setPositiveButton(mContext.getResources().getString(R.string.open_settings), new DialogInterface.OnClickListener() { // Open Settings 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 
        mContext.startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS)); 
       } 
      }) 
      .setNegativeButton(mContext.getResources().getString(R.string.dismiss), new DialogInterface.OnClickListener() { // Dismiss 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 
       } 
      }); 
    builder.create().show(); 
} 

private boolean checkPlayServices() { 
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); 
    int result = googleAPI.isGooglePlayServicesAvailable(mContext); 
    if (result != ConnectionResult.SUCCESS) { 
     if (googleAPI.isUserResolvableError(result)) { 
      googleAPI.getErrorDialog((MainActivity) mContext, result, MainActivity.REQUEST_CODE_RECOVER_PLAY_SERVICES).show(); 
     } 
     return false; 
    } 
    return true; 
} 
} 

Jetzt im MainActivity:

public class MainActivity extends FragmentActivity{ 


private GPSTracker locationTracker; 
public static final int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001; 


@Override 
protected void onResume() { 
    super.onResume(); 
    if (locationTracker == null) 
     locationTracker = new GPSTracker(MainActivity.this); 
    else 
     locationTracker.getLocation(); 
    LatLng latLong = new LatLng(locationTracker.getLatitude(), locationTracker.getLongitude()); // This is give you User Current 
} 

@Override 
protected void onPause() { 
    if (locationTracker != null) 
     locationTracker.stopUsingGPS(); 
    super.onPause(); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case REQUEST_CODE_RECOVER_PLAY_SERVICES: 
      if (resultCode == RESULT_CANCELED) { 
       UIHelper.showLongToastInCenter(MainActivity.this, getResources().getString(R.string.play_services_error)); // Google Play Services must be installed on this device 
       finish(); 
      } 
      break; 
    } 
    super.onActivityResult(requestCode, resultCode, data); 
} 
} 

In AndroidManifest.xml, fügen Sie diese folgenden Berechtigungen:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
+0

Okay, lassen Sie mich einmal versuchen, und ich werde Sie wissen lassen. –

+0

Es gibt eine Nullzeigerausnahme an protected void onPause() { if (locationTracker! = Null) locationTracker.stopUsingGPS(); // hier super.onPause(); } und public void stopUsingGPS() { if (locationManager! = Null) { locationManager.removeUpdates (GPSTracker.this); } } –

+0

Veröffentlichen Sie bitte Ihr Protokoll. Diese Zeile sollte nicht ausgeführt werden, da ich bereits nach locationTracker! = Null suche –

Verwandte Themen