2017-07-19 4 views
0

Wenn ich es starte, zeigt die Ausgabe, dass "Berechtigung verweigert", das ist in meinem anderen Teil.Ortung des GPS-Standorts meines Geräts

import android.content.pm.PackageManager; 
import android.location.Location; 
import android.os.Build; 
import android.support.annotation.NonNull; 
import android.support.annotation.Nullable; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 
import android.support.v4.content.ContextCompat; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MapsActivity extends FragmentActivity implements 
OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

private GoogleMap mMap; 
private GoogleApiClient client; 
private LocationRequest locationRequest; 
private Location lastLocation; 
private Marker currentLocationMarker; 
public static final int REQUEST_LOCATION_CODE=99; 

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
     checkLocationPermission(); 
    } 
    // Obtain the SupportMapFragment and get notified when the map is ready 
to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) 
getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] 
permissions, @NonNull int[] grantResults) { 
    switch (requestCode){ 
     case REQUEST_LOCATION_CODE: 
      if (grantResults.length > 0 && grantResults[0] == 
PackageManager.PERMISSION_GRANTED){ 
       //permission is granted 
       if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) == 
PackageManager.PERMISSION_GRANTED){ 
        if (client == null){ 
         buildGoogleApiClient(); 
        } 
        mMap.setMyLocationEnabled(true); 
       } 
      } 
      else //permission denied 
      { 
       Toast.makeText(this,"Permission denied", 
Toast.LENGTH_LONG).show(); 

      } 
      return; 
    } 
} 


/** 
* Manipulates the map once available. 
* This callback is triggered when the map is ready to be used. 
* This is where we can add markers or lines, add listeners or move the 
camera. In this case, 
* we just add a marker near Sydney, Australia. 
* If Google Play services is not installed on the device, the user will be 
prompted to install 
* it inside the SupportMapFragment. This method will only be triggered once 
    the user has 
* installed Google Play services and returned to the app. 
*/ 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
if 
(ContextCompat. 
checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATI 
ON) == PackageManager.PERMISSION_GRANTED) { 
     buildGoogleApiClient(); 
     mMap.setMyLocationEnabled(true); 
    } 
} 


protected synchronized void buildGoogleApiClient() 
{ 
    client = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 

    client.connect(); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    locationRequest = new LocationRequest(); 
    locationRequest.setInterval(1000); 
    locationRequest.setFastestInterval(1000); 

locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY 
); 

    if(ContextCompat.checkSelfPermission(this, 

Manifest 
.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED) 
{ 

     LocationServices.FusedLocationApi.requestLocationUpdates(client, 
locationRequest, this); 
    } 
} 



public boolean checkLocationPermission(){ 
    if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED){ 
     if 

(Activity 
Compat.shouldShowRequestPermissionRationale(this,Manifest.permission.A 
CCESS_FINE_LOCATION)){ 
      ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE); 
     } 
     else { 
      ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE); 

     } 
     return false; 
    } 
    else 
     return true; 
} 

@Override 
public void onLocationChanged(Location location) { 

    lastLocation = location; 

    if(currentLocationMarker != null) { 
     currentLocationMarker.remove(); 
    } 

    LatLng latLng = new 
LatLng(location.getLongitude(),location.getLongitude()); 
    MarkerOptions markerOptions = new MarkerOptions(); 
    markerOptions.position(latLng); 
    markerOptions.title("current location"); 



markerOptions.icon 
(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory 
.HUE_BLUE)); 
    currentLocationMarker=mMap.addMarker(markerOptions); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    mMap.animateCamera(CameraUpdateFactory.zoomBy(10)); 

    if (client != null){ 
     LocationServices.FusedLocationApi.removeLocationUpdates(client 
,this); 
    } 

} 
@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 
} 

und mein Android-Manifest-Datei

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.kerthi.map2"> 


<permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission 
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 


<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 


    <meta-data 
     android:name="com.google.android.geo.API_KEY" 
     android:value="@string/google_maps_key" /> 

    <activity 
     android:name=".MapsActivity" 
     android:label="@string/title_activity_maps"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    </application> 

    </manifest> 

ist Ich glaube, Sie haben einen Fehler in der if ist, bin ich nicht sicher. Bitte hilf mir bitte. Gibt es noch etwas, das ich hinzufügen sollte?

+0

Haben Sie Google API-Schlüssel hinzugefügt? ist der Schlüssel richtig? –

+0

@ AjilO.You brauchen keine API-Schlüssel für die GPS- – tyczj

+0

yup ich erhalte die Karte i – kerthivasan

Antwort

0

Manifestdatei

<?xml version="1.0" encoding="utf-8"?> 
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
     package="com.oit.test.mygoogle"> 

     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
     <uses-permission android:name="android.permission.INTERNET" /> 
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
     <permission 
      android:name="com.sa.com.oit.test.mygoogle.permission.MAPS_RECEIVE" 
      android:protectionLevel="signature"/> 


     <application 
      android:allowBackup="true" 
      android:icon="@mipmap/shiv" 
      android:label="@string/app_name" 
      android:roundIcon="@mipmap/ic_launcher_round" 
      android:supportsRtl="true" 
      android:theme="@style/AppTheme"> 

      <meta-data 
       android:name="com.google.android.geo.API_KEY" 
       android:value="@string/google_maps_key" /> 

      <activity 
       android:name=".MapsActivity" 
       android:label="@string/title_activity_maps"> 
      </activity> 

      <activity 
       android:name=".MapLocationActivity" 
       android:label="@string/title_activity_maps"> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
       </intent-filter> 
      </activity> 

     </application> 

    </manifest> 

MainActivity

package com.oit.test.mygoogle; 

import android.*; 
import android.Manifest; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.annotation.Nullable; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.LocationSource; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.CameraPosition; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MapLocationActivity extends AppCompatActivity 


     implements OnMapReadyCallback, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    LocationListener 

{ 

    GoogleMap mGoogleMap; 
    SupportMapFragment mapFrag; 
    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationManager locationManager; 
    public static final int REQUEST_LOCATION = 100; 
    double mLatitude; 
    double mLongitude; 

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

     locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
     { 
      checkLocationPermission(); 
     } 
     else 
     { 
      if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
      { 
       showGPSDisabledAlertToUser(); 
      } 
     } 

     mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFrag.getMapAsync(this); 
    } 

    private void showGPSDisabledAlertToUser() 
    { 
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?") 
       .setCancelable(false) 
       .setPositiveButton("Settings", new DialogInterface.OnClickListener() 
       { 
        public void onClick(DialogInterface dialog, int id) 
        { 
         Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(callGPSSettingIntent); 

         mapFrag.getMapAsync(MapLocationActivity.this); 
        } 
       }); 
     alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface dialog, int id) 
      { 
       dialog.cancel(); 
      } 
     }); 
     AlertDialog alert = alertDialogBuilder.create(); 
     alert.show(); 
    } 

    @Override 
    public void onPause() 
    { 
     super.onPause(); 

     //stop location updates when Activity is no longer active 
     if (mGoogleApiClient != null) 
     { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) 
    { 
     mGoogleMap=googleMap; 
     mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     //Initialize Google Play Services 
     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
     { 
      if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
      { 
       buildGoogleApiClient(); 
       mGoogleMap.setMyLocationEnabled(true); 
      } 
     } 
     else 
     { 
      buildGoogleApiClient(); 
      mGoogleMap.setMyLocationEnabled(true); 
     } 

     mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { 
      @Override 
      public boolean onMyLocationButtonClick() { 
       LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
       Criteria criteria = new Criteria(); 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION); 
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); 
        //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method 
       } else { 
        mGoogleMap.setMyLocationEnabled(true); 
        //Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true)); 
        LatLng coordinate = new LatLng(mLatitude, mLongitude); 
        CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 10); 
        mGoogleMap.animateCamera(yourLocation); 
        return true; 

       } 
       return false; 
      } 
     }); 
    } 

    protected synchronized void buildGoogleApiClient() 
    { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) 
    { 
     mLocationRequest = new LocationRequest(); 
    /*  mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000);*/ 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
     { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) {} 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) {} 

    @Override 
    public void onLocationChanged(Location location) 
    { 
     mLastLocation = location; 
    /* if (mCurrLocationMarker != null) 
     { 
      mCurrLocationMarker.remove(); 
     }*/ 
     LatLng opt = new LatLng(22.57, 88.43); 
     mGoogleMap.addMarker(new MarkerOptions().position(opt).title("Shivi").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker))); 

     LatLng opt2 = new LatLng(22.50, 88.53); 
     mGoogleMap.addMarker(new MarkerOptions().position(opt2).title("Sarthak").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker))); 

     LatLng opt3 = new LatLng(22.67, 88.35); 
     mGoogleMap.addMarker(new MarkerOptions().position(opt3).title("Mitra").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker))); 

     LatLng opt4 = new LatLng(22.47, 88.43); 
     mGoogleMap.addMarker(new MarkerOptions().position(opt4).title("Boss").icon(BitmapDescriptorFactory.fromResource(R.mipmap.marker))); 
     mLatitude = location.getLatitude(); 
     mLongitude = location.getLongitude(); 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Position"); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); 

     CameraPosition cameraPosition = new CameraPosition.Builder() 
       .target(latLng)  // Sets the center of the map to location user 
       .zoom(10)     // Sets the zoom 
       .build();     // Creates a CameraPosition from the builder 
     mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
     /* //Place current location marker 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Position"); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); 

     //move map camera 
     mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));*/ 

     //stop location updates 
     if (mGoogleApiClient != null) 
     { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 
    } 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

    public boolean checkLocationPermission() 
    { 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
     { 
      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) 
      { 
       // Show an expanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

       //Prompt the user once explanation has been shown 
       ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      else 
      { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } 
     else 
     { 
      if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
      { 
       showGPSDisabledAlertToUser(); 
      } 

      return true; 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) 
    { 
     switch (requestCode) 
     { 
      case MY_PERMISSIONS_REQUEST_LOCATION: 
      { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
       { 
        // permission was granted, yay! Do the 
        // contacts-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) 
        { 

         if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
         { 
          showGPSDisabledAlertToUser(); 
         } 

         if (mGoogleApiClient == null) 
         { 
          buildGoogleApiClient(); 
         } 
         mGoogleMap.setMyLocationEnabled(true); 
        } 
       } 
       else 
       { 
        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 
      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 
} 
+0

Bitte kurz erklären, was Sie in diesem Thema geschrieben Manifest-Datei geändert haben zu lösen „Zugriff verweigert“ -Ausgabe –

+0

fügen Sie diese erste –

+0

Abhängigkeiten Abhängigkeiten { kompilieren filetree (dir: 'libs', include: ['* .jar']) androidTestCompile ('com.android.support.test.espresso: espresso-core: 2.2.2', { ausschließen Gruppe: 'com.android. support ', modul:' support-annotations ' }) kompilieren' com.android.support:appcompat-v7:26.+ ' kompilieren' com.google.android.gms: play-services-maps: 8.4.0 ' testCompile' junit: junit: 4.12 ' kompilieren' com.google.android.gms: play-servi ces: 8.4.0 ' kompilieren' com.google.android.gms: play-services-location: 8.4.0 ' } Abhängigkeiten {compile' com.android.support:support-annotations:24.2.0 ' } –

Verwandte Themen