2016-09-08 19 views
-1

私はアプリを開発しています、ここで私はGoogleマップを使用しています。 Googleマップは現在の場所を他の端末に表示しますが、現在の位置は表示されません(6.0)。Googleマップはアンドロイドでは表示されませんmarshmallow(6.0)?

marshmallow(6.0)では、アプリを開くとマップが表示されますが、現在の位置は表示されません。

私はアプリを開くと、現在の場所を表示する必要がありますすべてのデバイスでGoogleマップの現在の場所を表示する。

どうすればよいですか?

java file 
public class Maps_Activity extends FragmentActivity implements 
     OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     GoogleMap.OnMarkerDragListener, 
     GoogleMap.OnMapLongClickListener, 
     View.OnClickListener { 

    //Our Map 
    private GoogleMap mMap; 
    public static final int REQUEST_ID_ACCESS_COURSE_FINE_LOCATION = 100; 

    //To store longitude and latitude from map 
    private double longitude; 
    private double latitude; 
    String caddress; 

    //Buttons 
    private ImageButton buttonSave; 
    private ImageButton buttonCurrent; 
    private ImageButton buttonView; 

    private Button btnProceed, btnskip, btnClocation; 

    String strAdd; 
    TextView tvmap,textview; 

    private boolean loggedIn = false; 
    public static String email; 


    private ProgressDialog myProgress; 

    //Google ApiClient 
    private GoogleApiClient googleApiClient; 
    SupportMapFragment mapFragment; 


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

     tvmap=(TextView)findViewById(R.id.tv_map); 
     textview=(TextView)findViewById(R.id.textView_euser); 

     //progress bar 
     myProgress = new ProgressDialog(this); 
     myProgress.setTitle("Map Loading ..."); 
     myProgress.setMessage("Please wait..."); 
     myProgress.setCancelable(true); 
     // Display Progress Bar. 
     myProgress.show(); 

     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     //Initializing googleapi client 
     googleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

     //googleapi gps 

    /* googleApiClient = new GoogleApiClient 
       .Builder(this) 
       .enableAutoManage(this, 34992, this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 
     locationChecker(googleApiClient, MapsActivity.this); */ 

     //Initializing views and adding onclick listeners 
     btnProceed=(Button)findViewById(R.id.button_proceed); 
     btnskip=(Button)findViewById(R.id.button_skip); 
     // btnClocation=(Button)findViewById(R.id.button_clocation); 

     btnProceed.setOnClickListener(this); 
     btnskip.setOnClickListener(this); 
     // btnClocation.setOnClickListener(this); 

     SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); 
     loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false); 
     email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available"); 
     textview.setText(email); 

    } 

    @Override 
    protected void onResume() { 

     LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
     boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     if(!enabled) { 
      showDialogGPS(); 
     } 

     super.onResume(); 
    } 

    private void showDialogGPS() { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setCancelable(false); 
     builder.setTitle("Enable GPS"); 
     builder.setMessage("Please enable GPS"); 
     builder.setInverseBackgroundForced(true); 
     builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       startActivity(
         new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
       getCurrentLocation(); 
       moveMap(); 
      } 
     }); 
     builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 


    @Override 
    public void onClick(View v) { 
     if(v == btnProceed){ 
     // getCurrentLocation(); 
     // moveMap(); 
      if (loggedIn) { 
       //We will start the Profile Activity 

       submitForm(); 
       Intent i=new Intent(Maps_Activity.this,Search_ActivityND.class); 
       startActivity(i); 
      } 

     } 
     else if(v == btnskip){ 

      btnclick_skip(); 
     } 

    } 

    //dalete alert 
    private void btnclick_skip(){ 

     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     alertDialogBuilder.setMessage("Are you fine this Location?"); 
     alertDialogBuilder.setPositiveButton("Yes", 
       new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface arg0, int arg1) { 

         // new JSONParserD().execute(); 
         //Starting login activity 
         Intent intent = new Intent(Maps_Activity.this, Search_ActivityND.class); 
         startActivity(intent); 
         // if (loggedIn) { 
         //  Intent intent = new Intent(MapsActivity.this, Home.class); 
         //  startActivity(intent); 
         // } 

        } 
       }); 

     alertDialogBuilder.setNegativeButton("No", 
       new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface arg0, int arg1) { 

        } 
       }); 

     //Showing the alert dialog 
     AlertDialog alertDialog = alertDialogBuilder.create(); 
     alertDialog.show(); 
    } 


    //saving to database 
    private void submitForm() { 

     caddress = tvmap.getText().toString(); 
     email = textview.getText().toString(); 
     // Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show(); 
     new MapAsync(this).execute(caddress,email); 
    } 

    @Override 
    protected void onStart() { 
     googleApiClient.connect(); 
     super.onStart(); 
    } 

    @Override 
    protected void onStop() { 
     googleApiClient.disconnect(); 
     super.onStop(); 
    } 

    //Getting current location 
    private void getCurrentLocation() { 
     mMap.clear(); 
     //Creating a location object 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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 = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

     if (location != null) { 
      //Getting longitude and latitude 
      longitude = location.getLongitude(); 
      latitude = location.getLatitude(); 

      // tvmap.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude()); 

      strAdd = getCompleteAddressString(latitude, longitude); 
      tvmap.setText("Current Address : " + strAdd); 

      //moving the map to location 
      moveMap(); 
     } 

    } 

    //Function to move the map 
    private void moveMap() { 
     //String to display current latitude and longitude 
     String msg = latitude + ", "+longitude; 

     //Creating a LatLng Object to store Coordinates 
     LatLng latLng = new LatLng(latitude, longitude); 

     //Adding marker to map 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) //setting position 
       .draggable(true) //Making the marker draggable 
       .title("Current Location")); //Adding a title 

     //Moving the camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

     //Animating the camera 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 

    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 

     mMap = googleMap; 
     LatLng latLng = new LatLng(-34, 151); 
     mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.setOnMarkerDragListener(this); 
     mMap.setOnMapLongClickListener(this); 

    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     getCurrentLocation(); 
     myProgress.dismiss(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onMapLongClick(LatLng latLng) { 
     //Clearing all the markers 
     mMap.clear(); 

     //Adding a new marker to the current pressed position 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) 
       .draggable(true)); 
    } 

    @Override 
    public void onMarkerDragStart(Marker marker) { 

    } 

    @Override 
    public void onMarkerDrag(Marker marker) { 

    } 

    @Override 
    public void onMarkerDragEnd(Marker marker) { 
     //Getting the coordinates 
     latitude = marker.getPosition().latitude; 
     longitude = marker.getPosition().longitude; 

     //Moving the map 
     moveMap(); 
    } 

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) { 
     String strAdd = ""; 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     try { 
      List<Address> addresses = geocoder 
        .getFromLocation(LATITUDE, LONGITUDE, 1); 
      if (addresses != null) { 
       android.location.Address returnedAddress = addresses.get(0); 
       StringBuilder strReturnedAddress = new StringBuilder(""); 

       for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { 
        strReturnedAddress 
          .append(returnedAddress.getAddressLine(i)).append(
          "\n"); 
       } 
       strAdd = strReturnedAddress.toString(); 
       // Log.w("My Current loction address", 
       //   "" + strReturnedAddress.toString()); 
      } else { 
       // Log.w("My Current loction address", "No Address returned!"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      // Log.w("My Current loction address", "Canont get Address!"); 
     } 
     return strAdd; 
    } 
    } 


manifest file 

    apply plugin: 'com.android.application' 

    android { 
     compileSdkVersion 23 
     buildToolsVersion "24.0.0" 

     defaultConfig { 
      applicationId "com.example.user.mangoair_t" 
      minSdkVersion 14 
      targetSdkVersion 23 
      versionCode 1 
      versionName "1.0" 
      multiDexEnabled true 
     } 

     buildTypes { 
      release { 
       minifyEnabled false 
       proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
      } 
     } 
    } 


    android { 
     useLibrary 'org.apache.http.legacy' 
    } 

    dependencies { 

     testCompile 'junit:junit:4.12' 
     compile 'com.android.support:appcompat-v7:23.4.0' 
     compile 'com.android.support:design:23.4.0' 

     compile 'com.google.http-client:google-http-client-android:+' 

     compile 'com.google.api-client:google-api-client-android:+' 

     compile 'com.google.api-client:google-api-client-gson:+' 

     compile 'com.google.code.gson:gson:2.2.4' 

     compile fileTree(dir: 'libs', include: ['*.jar']) 
     compile 'com.android.support:appcompat-v7:23.1.1' 
     compile fileTree(include: ['*.jar'], dir: 'libs') 
     compile "cz.msebera.android:httpclient:4.4.1.1" 
     compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1' 

     compile 'com.mcxiaoke.volley:library-aar:1.0.0' 

     compile 'com.android.support:design:23.2.0' 
     testCompile 'junit:junit:4.12' 
     compile 'com.android.support:appcompat-v7:23.2.0' 
     compile 'com.android.support:design:23.2.0' 

     // compile 'com.google.android.gms:play-services:9.0.2' 
     compile 'com.google.android.gms:play-services:8.4.0' 
     compile 'com.android.support:appcompat-v7:23.4.0' 

     compile 'com.android.support:multidex:1.0.0' 

    } 
+0

は設定 –

+0

実行時許可 –

+0

あなたはGPS位置の設定を意味するのですから、場所の許可を有効にしますか? – rohiH

答えて

1

あなたtargetSDKが23である場合は、実行時に場所許可を確認する必要があります。デフォルトでは許可されていません。あなたが許可を要求するためにこのような何かを行う必要がありますあなたの場合は

:次に

int hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION); 
    if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) { 
     requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 
       REQUEST_CODE_ASK_PERMISSIONS); 
    } 

結果はチェックと要求許可のこの偉大なチュートリアルを読んでください詳細については

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {} 

で返されますAndroid 6.0の場合New Android Runtime permission

+0

実行時にこの場所のアクセス許可を確認するにはどうすればよいですか? – rohiH

+0

https://android-arsenal.com/details/1/3234このリンクに従うと、実行時の許可に使用します。 – Pawanpreet

+0

@rohiH最新の回答を見る – TOP

0

実行時のアクセス許可でこれを試すことができます:

 public void checkPermission() { 
    if (ContextCompat.checkSelfPermission(YourActivity.this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(YourActivity.this, 
       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. 

     } 
} 
2

Android 6.0以降では、実行時にアクセス許可をチェックする必要があると思います。以下は、実行時にパーミッションをチェックするためのスニペットです。

PackageManager pm = getApplicationContext().getPackageManager(); 
int hasCoarseLocPerm = pm.checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,getApplicationContext().getPackageName()); 
int hasFineLocPerm = pm.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION,getApplicationContext().getPackageName()); 
if (!(hasCoarseLocPerm == PackageManager.PERMISSION_GRANTED&&hasFineLocPerm == PackageManager.PERMISSION_GRANTED)) { 
      // do stuff 
      Toast.makeText(PreferencesActivity.this, "Please provide all the permissions required", Toast.LENGTH_LONG).show(); 
} 
0

注:marashmallowまたは上記これらの権限で実行時間を与え、許可がmainfest

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

ランタイム

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 10; 

private String[] permissions= new String[]{ 
       Manifest.permission.ACCESS_COARSE_LOCATION, 
    Manifest.permission.ACCESS_FINE_LOCATION}; 


if (checkPermissions()) 
     // permissions granted.  
} 

private boolean checkPermissions() { 
    int result; 
    List<String> listPermissionsNeeded = new ArrayList<>(); 
    for (String p:permissions) { 
     result = ContextCompat.checkSelfPermission(this,p); 
     if (result != PackageManager.PERMISSION_GRANTED) { 
      listPermissionsNeeded.add(p); 
     } 
    } 
    if (!listPermissionsNeeded.isEmpty()) { 
     ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); 
     return false; 
    } 
    return true; 
} 

を付与されたときにコードを置きます

0

Android Mを実行していますか?その場合は、マニフェストにpermissionsを宣言するだけでは不十分であるためです。一部のアクセス許可については、ユーザーに明示的にユーザーに問い合わせる必要があります。run-time

実行時のアクセス許可はLinkにチェックしてください。

コードスニペット

この世界を定義します。

private static final int PERMISSION_REQUEST_CODE = 1; 

そして、この意志のonCreateになります。

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

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(Maps_Activity.this, 
      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. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(Maps_Activity.this, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       PERMISSION_REQUEST_CODE); 

     // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

と書き換えてonRequestPermissionsResult。

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case PERMISSION_REQUEST_CODE: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! 

      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 
関連する問題