android - 如何请求 GPS 许可并在完成后显示 map

标签 android google-maps

我正在研究 map ,我是 map 新手。我正在显示 map (v1)并且工作完美但我的问题是棉花糖我必须询问运行时许可我正在显示许可对话框运行时但是在许可 ionic 显示之后同时 map 也在显示和崩溃因为在显示许可对话框 map 位置甚至工作之后我不能允许我的问题是,如果在没有渗透的情况下授予许可,我想要显示 map 总是征求许可。 我的代码是。

     public class MapsActivity extends FragmentActivity implements LocationListener {

GoogleMap googleMap;
String username, password;
JSONParser jsonParser = new JSONParser();
SessionManager session;
Location location;
String bestProvider;
LocationManager locationManager;

;
SharedPreferences.Editor editor;
private static final int MY_PERMISSION_REQUEST_READ_FINE_LOCATION = 111;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (ContextCompat.checkSelfPermission(getApplication(),
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission( getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.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(MapsActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    MY_PERMISSION_REQUEST_READ_FINE_LOCATION);

            // MY_PERMISSION_REQUEST_READ_FINE_LOCATION is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    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;
    }
    //show error dialog if GoolglePlayServices not available
    if (!isGooglePlayServicesAvailable()) {
        finish();
    }
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();
    }
    setContentView(R.layout.activity_maps);
    SupportMapFragment supportMapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);

    googleMap = supportMapFragment.getMap();
    googleMap.setMyLocationEnabled(true);
    session = new SessionManager(getApplicationContext());
    HashMap<String, String> user = session.getUserDetails();
    username = user.get(SessionManager.KEY_NAME);
    password = user.get(SessionManager.KEY_PASSWORD);



    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    bestProvider = locationManager.getBestProvider(criteria, true);

    location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSION_REQUEST_READ_FINE_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.

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

@Override
public void onLocationChanged(Location location) {

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
//    LatLng initialLoc= googleMap.getCameraPosition().target;

    //   googleMap.addMarker(new MarkerOptions().position(latLng));*/
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(60));

//    LatLng coordinate = new LatLng(lat, lng); //Store these lat lng values somewhere. These should be constant.
    CameraUpdate location1 = CameraUpdateFactory.newLatLngZoom(
            latLng, 20);
    googleMap.animateCamera(location1);




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    ActionBar actionBar = getActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayShowHomeEnabled(false);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    //actionBar.setDisplayUseLogoEnabled(false);
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        case R.id.notify_setting:
            new Logout().execute();
            return true;
        case R.id.changepassword:
            Intent nextscreen = new Intent(getApplicationContext(), Changepassword.class);
            startActivity(nextscreen);
            return true;

    }
    return false;
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

private boolean isGooglePlayServicesAvailable() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (ConnectionResult.SUCCESS == status) {
        return true;
    } else {
        GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
        return false;
    }
}

class Logout extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(), "Please Wait For Logout", Toast.LENGTH_SHORT).show();
        //pDialog = new ProgressDialog(MainActivity.this);
        //pDialog.setMessage("Please Wait..");
        //pDialog.setIndeterminate(false);
        //pDialog.setCancelable(true);
        //pDialog.show();


    }

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
        if (AllChanges.checkinternet()) {
            // Building Parameters

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            JSONObject json = jsonParser.makeHttpRequest(AllChanges.Url + "?r=api/getresponse&model=gpslogout&type=logout",
                    "POST", params);

            if (json != null) {
                // check for success tag
                try {
                    int success = json.getInt("success");

                    if (success == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                session.logoutUser();

                                cancelAlarmManager();
                                finish();

                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "Try After Some Time", Toast.LENGTH_LONG).show();

                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Check Internet Connection", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Check Internet Connection", Toast.LENGTH_SHORT).show();

                }
            });
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done


    }

}

public void cancelAlarmManager() {
    Log.d("hi", "cancelAlarmManager");
    Context context = getBaseContext();
    Intent gpsTrackerIntent = new Intent(context, GpsTrackerAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, gpsTrackerIntent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
    SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
    editor.putBoolean("currentlyTracking", false);
    editor.apply();
}

@Override
protected void onResume() {
    super.onResume();
    if (location != null) {
        onLocationChanged(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;
    }
    locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

最佳答案

试试这个,

    private Context mContext=YourActivity.this;

    private static final int REQUEST = 112;


    if (Build.VERSION.SDK_INT >= 23) {
        String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION,android.Manifest.permission.ACCESS_FINE_LOCATION};
        if (!hasPermissions(mContext, PERMISSIONS)) {
            ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
        } else {
            //call get location here
        }
    } else {
        //call get location here
    }

获取权限结果

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //call get location here
                } else {
                    Toast.makeText(mContext, "The app was not allowed to access your location", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

检查棉花糖的权限

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

list

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

获取位置

    public void getLocation()
    {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        bestProvider = locationManager.getBestProvider(criteria, true);

        location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }

关于android - 如何请求 GPS 许可并在完成后显示 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43039149/

相关文章:

Android:如何检查谷歌是否可用?

Android Place API : PlaceDetectionApi. getCurrentPlace() 始终不返回任何结果

java - 使用 GeoJson 向 google map 添加标记

javascript - 在 HTML5 和 JavaScript 中使用 Google Maps Indoor Map API

android - android.view.InflateException膨胀类com.android.internal.widget.ActionBarContextView发生错误

android - 项目在编译时,Gradle出现了一些错误,没有遇到类似的问题

java - Android Espresso 拖放错误注入(inject)事件

安卓 : Move arrow's end point and start point on user's touch event

google-maps - 如何更改 Google map 中 KML 和图 block 叠加层的分层?

reactjs - react 谷歌地图 : Can't get bounds