简体   繁体   English

向onMapsReady android询问运行时权限

[英]ask runtime permissions for onMapsReady android

i have a phone with android 6.0, and the method onMapReady is not execute, because i think need runtime permissions, and i dont know how to do that, this is my code 我有一个装有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);

    }

}

maybe the onmylocation needs permissions ithink 也许onmylocation需要权限思考

ps: works perfect with android 4.4, the problem is with android 6.0 or higher ps:适用于android 4.4,问题出在android 6.0或更高版本

I also struggled with the runtime permissions when upgrading my app to a new Android version. 在将应用程序升级到新的Android版本时,我还遇到了运行时权限问题。

But I found this post very helpful: 但是我发现这篇文章很有帮助:

https://inducesmile.com/android/android-6-marshmallow-runtime-permissions-request-example/ (The code below comes from this). https://inducesmile.com/android/android-6-marshmallow-runtime-permissions-request-example/ (以下代码来自此)。

Basically, you need to check if you have the permissions in your App when you need them (perhaps during startup in your case) with code such as this; 基本上,您需要使用以下代码检查是否需要在应用程序中拥有权限(可能在启动时针对您的情况);

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

Then, you need to handle a response in an onRequestPermissionsResult method 然后,您需要在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.
            }
        }
    }
}

Don't forget that you still need the permissions to be specified in your MANIFEST file. 不要忘记,您仍然需要在MANIFEST文件中指定权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM