简体   繁体   English

第一次在棉花糖中启动应用程序时如何获取位置信息

[英]How to get location access when starting the app for the first time in marshmallow

I am crating an app. 我正在创建一个应用。 I am not getting current location when i installed app and then open it and allow the location access permission but showing only map.After reopen the app then current location is showing. 安装应用程序然后打开它并允许位置访问权限时,我没有得到当前位置,但仅显示地图。重新打开应用程序后,将显示当前位置。 using following code- 使用以下代码-

     public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;

    LatLng latLng;
    GoogleMap mMap;
    SupportMapFragment mFragment;
    Marker CurrentMarker;

    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

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

       // Button request_permission = (Button)findViewById(R.id.request_permission);

        //request_permission.setOnClickListener(this);

        if (!checkPermission()) {

            requestPermission();

        } else {

            Toast.makeText(this,"Permission already granted.",Toast.LENGTH_SHORT).show();

        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        //final int LOCATION_PERMISSION_REQUEST_CODE = 100;
       // ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION},
              //  LOCATION_PERMISSION_REQUEST_CODE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

           return;
        }
        mMap.setMyLocationEnabled(true);
        buildGoogleApiClient();
        mGoogleApiClient.connect();

    }

    private void buildGoogleApiClient() {

        // TODO Auto-generated method stub
        Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {


        Toast.makeText(this, "Onconnection", Toast.LENGTH_SHORT).show();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation != null){
            latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Location");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            CurrentMarker = mMap.addMarker(markerOptions);
        }
        mLocationRequest = new LocationRequest();
        //mLocationRequest.setInterval(5000);
       // mLocationRequest.setFastestInterval(3000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onLocationChanged(Location location) {

        if (CurrentMarker != null){
            CurrentMarker.remove();
        }
        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));
        CurrentMarker = mMap.addMarker(markerOptions);
        Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();

        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }


    private boolean checkPermission(){
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED){

            return true;

        } else {

            return false;

        }
    }

    private void requestPermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){

            Toast.makeText(this,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();

        } else {

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

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {



                } else {



                }
                break;
        }
    }
}

Please tell me how to get location when i installed and then open it for first time.Using my source code. 请告诉我安装后如何获取位置,然后首次打开它。使用我的源代码。

Thanks 谢谢

In marshmallow you can not get location until user permit location access to the application in runtime. 在棉花糖中,除非用户在运行时允许对应用程序的位置访问,否则无法获取位置。 As user permit location permission restart your activity 当用户允许位置权限重新启动活动时

  Intent intent= new Intent(MainActivity.this,MainActivity.class);
    startActivity(intent);
    finish();

Why did not show first time : Because you didn't handle after granting. 为什么没有第一次显示:因为您在授予后没有处理。

Why did you show on second time : Because you've previously granted the permission. 您为何第二次显示:因为您之前已授予许可。

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // TRY GETTING THE LOCATION HERE ON FIRST TIME (AFTER GRANTING)
             Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            } else {}
            break;
    }
}

暂无
暂无

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

相关问题 第一次启动我的应用程序时片段没有显示 - Fragment showing nothing when starting my app for first time 删除棉花糖当前位置的运行时权限 - Remove Run Time Permission for current location in Marshmallow 应用程序打开时如何以编程方式恢复位置信息访问 - How to resume Location access programmatically when app open 首次启动时location返回null - location returns null when started the first time MediaPlayer - 如何在第一次启动应用程序时显示警报对话框 - MediaPlayer - How to show a alert dialoge when app is launched first time 如何处理适用于OS Marshmallow及更高版本的Appium android测试中的App权限弹出窗口(系统弹出窗口,例如设备位置/联系人列表)? - How to handle App permission pop ups (system popups like device location/contact list) in Appium android tests for OS Marshmallow and above? 如何授予对棉花糖上运行的android应用的权限? - How to grant permissions to android app running on Marshmallow? FATAL EXCEPTION for AndroidRuntime 启动应用程序一段时间并导致崩溃 - FATAL EXCEPTION for AndroidRuntime when starting the app for a period of time and lead to crash AsyncTask(update)仅在首次打开应用程序时有效,但5秒钟后不会更新 - AsyncTask(update) works only when app get opened first time, but it is not updating after 5 sec 当应用重新启动并且用户已经被授予位置访问权限时,如何再次启动服务 - How to start service again when App Restarts and User already Granted Location access
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM