询问onMapsReady android的运行时权限

时间:2016-11-07 13:04:53

标签: java android google-maps

我有一个带有android 6.0的手机,并且onMapReady的方法没有执行,因为我认为需要运行时权限,我不知道该怎么做,这是我的代码

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {

    GoogleMap map;
    GoogleApiClient mGoogleApiClient;
    String email;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

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

        FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
        //obtener datos para la barra
        if(user != null) {

            String nombre=user.getDisplayName();
            email=user.getEmail();
            Uri foto=user.getPhotoUrl();

            NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
            View hView =  navigationsView.getHeaderView(0);
            TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
            TextView name=(TextView) hView.findViewById(R.id.txtNombre);
            ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);

            name.setText(nombre);
            nav_user.setText(email);
            Picasso.with(this).load(foto).into(img_user);
        }
        else {
            SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
            email=loginbdd.getString("nombre","");
            String nombre=loginbdd.getString("mail","");

            NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
            View hView =  navigationsView.getHeaderView(0);
            TextView nav_user = (TextView)hView.findViewById(R.id.txtMail);
            TextView name=(TextView) hView.findViewById(R.id.txtNombre);
            ImageView img_user = (ImageView)hView.findViewById(R.id.profile_image);

            nav_user.setText(email);
            name.setText(nombre);
        }

    }

    private void goLogin() {
        Intent intent = new Intent(this, Login.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(R.drawable.cerrar).setTitle("Cerrar Aplicación").setMessage("Deseas cerrar CicloMapp?")
                    .setCancelable(true).setPositiveButton("Si", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.endSession) {
            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(R.drawable.cerrar)
                    .setTitle("Cerrar sessión")
                    .setMessage("Deseas cerrar sesión?")
                    .setCancelable(true)
                    .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
                            if(user!= null){
                                LoginManager.getInstance().logOut();
                                FirebaseAuth.getInstance().signOut();
                                goLogin();
                            }else{
                                SharedPreferences loginbdd=getSharedPreferences("login", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor=loginbdd.edit();
                                editor.remove("inicio");
                                editor.commit();
                                goLogin();
                            }
                        }

                    })
                    .setNegativeButton("No", null).show();
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.AgregarRuta) {

        } else if (id == R.id.ValorarRuta) {
            Intent i = new Intent(MainActivity.this, Valoraraciones.class);
            i.putExtra("correo", email);
            startActivity(i);
        } else if (id == R.id.ReportarRuta) {
            Intent i = new Intent(MainActivity.this, Reportar.class);
            i.putExtra("correos", email);
            startActivity(i);
        } else if (id == R.id.Eventos) {

        } else if (id == R.id.Refresco) {

        } else if (id == R.id.Leyes) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onMapReady(final GoogleMap googleMap) {
        map=googleMap;
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        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) {
            return;
        }
        map.getUiSettings().setMapToolbarEnabled(false);
        map.getUiSettings().setMyLocationButtonEnabled(true);
        map.setMyLocationEnabled(true);
        map.getUiSettings().setZoomControlsEnabled(true);
        CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(-33.447487,-70.673676));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
        map.moveCamera(center);
        map.animateCamera(zoom);
        Polyline po = new Polyline();
        po.AddPolyline(map);

        int height = 50;
        int width = 50;
        BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.mruta);
        Bitmap b = bitmapdraw.getBitmap();

        Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
        final Marcadores ma=new Marcadores();
        ma.MarcadoreBdd(map,smallMarker);

    }

}

也许onmylocation需要权限ithink

ps:与android 4.4完美配合,问题在于android 6.0或更高版本

1 个答案:

答案 0 :(得分:0)

在将我的应用程序升级到新的Android版本时,我也在努力使用运行时权限。

但我发现这篇文章非常有用:

https://inducesmile.com/android/android-6-marshmallow-runtime-permissions-request-example/ (以下代码来自于此。)

基本上,您需要在需要时检查您的应用程序中是否具有权限(可能在您的情况下启动时),并使用此代码;

if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}

然后,您需要在onRequestPermissionsResult方法中处理响应

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == MY_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //You have permission, so continue
        }else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
            if (ActivityCompat.shouldShowRequestPermissionRationale(WebActivity.this, Manifest.permission.RECORD_AUDIO)) {
                //Show an explanation to the user *asynchronously*
                ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
            }else{
                //Never ask again and handle your app without permission.
            }
        }
    }
}

不要忘记您仍需要在MANIFEST文件中指定权限。