Как узнать текущее местоположение в Android Studio с помощью эмулятора NOX? - PullRequest
0 голосов
/ 10 ноября 2019

Как узнать текущее местоположение в Android Studio с помощью эмулятора NOX? Моя карта была отображена и отображается правильно, у меня нет проблем с этим, но мое текущее местоположение неверно. Это устанавливает местоположение в Лос-Анджелес, Калифорния, и я из Филиппин. Как я могу уладить это?

Вот содержимое моего кода:

@Override
    public void onMapReady(GoogleMap googleMap) {
        Log.d(TAG, "onMapReady: Map is Ready");
        mMap = googleMap;

        if(mLocationPermssionGranted){
            getDeviceLocation();

            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);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
        }
    }

    private static final String TAG = "CommuterHomeActivity";

    //This message will return to the user if uses wrong google play services version
    private static final int ERROR_DIALOG_REQUEST = 9001;

    //Declare variable to handle the id of Bottom Navigation View Palette
    BottomNavigationView bottomNavigationView;

    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;

    //variables
    private Boolean mLocationPermssionGranted = false;
    private GoogleMap mMap;
    private FusedLocationProviderClient mfusedLocationProviderClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commuter_home);
        MultiDex.install(this);

        bottomNavigationView = findViewById(R.id.bottomNavBar);

        //Set clicked navigation as active throught bolding the icon when a user currently on that page
        Menu menu = bottomNavigationView.getMenu();
        MenuItem menuItem = menu.getItem(0);
        menuItem.setChecked(true);

        if(isGooglePlayVersionCompatible()){
            initMap();
        }
        getLocationPermission();

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch (menuItem.getItemId())
                {
                    case R.id.ic_history:
                        Intent intent2 = new Intent(CommuterHomeActivity.this, CommuterTravelHistoryActivity.class);
                        startActivity(intent2);
                        break;
                    case R.id.ic_book:
                        Intent intent3 = new Intent(CommuterHomeActivity.this, CommuterBookRideActivity.class);
                        startActivity(intent3);
                        break;
                    case R.id.ic_account:
                        Intent intent4 = new Intent(CommuterHomeActivity.this, CommuterProfileActivity.class);
                        startActivity(intent4);
                        break;
                    case R.id.ic_sign:
                        Intent intent5 = new Intent(CommuterHomeActivity.this, CommuterTrafficRulesActivity.class);
                        startActivity(intent5);
                        break;
                }

                return false;
            }
        });
    }

    private void getDeviceLocation(){
        Log.d(TAG, "getDeviceLocation: Getting the device current location");

        mfusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try{
            if(mLocationPermssionGranted)
            {
                Task location = mfusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if(task.isSuccessful()){
                            Location currentLocation = (Location) task.getResult();
                            Log.d(TAG, "onComplete: Found location!");
                            moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM);
                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(CommuterHomeActivity.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }catch(SecurityException e){
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
        }
    }

    private void moveCamera(LatLng latLng, float zoom){
        Log.d(TAG, "moveCamera: Moving the camera to lat: " + latLng.latitude + ", long: " + latLng.longitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void initMap(){
        Log.d(TAG, "initMap: Initializing Map");
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        supportMapFragment.getMapAsync(CommuterHomeActivity.this);
    }

    //Check for Google Play Services Version via returning boolean
    public boolean isGooglePlayVersionCompatible(){
        Log.d(TAG, "isGooglePlayVersionCompatible: Checking Google Play Services Version");

        int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(CommuterHomeActivity.this);

        if(available == ConnectionResult.SUCCESS){
            //Everything is fine and the user can make map requests
            Log.d(TAG, "isGooglePlayVersionCompatible: Google Play Services is Working Properly...");
            return true;
        }else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
            //An error occured but we can fix it
            Log.d(TAG, "isGooglePlayVersionCompatible: An Error occured but we can fix it!");
            Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(CommuterHomeActivity.this, available, ERROR_DIALOG_REQUEST);
            dialog.show();
        }else{
            Toast.makeText(this, "You can not make Map Request!", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    //Get Location Permission
    private void getLocationPermission(){
        Log.d(TAG, "getLocationPermission: Getting Location Permissions");
        String [] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            if(ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            {
                mLocationPermssionGranted = true;
                initMap();
            }else{
                ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
            }
        }else{
            ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: Called.");
        mLocationPermssionGranted = false;

        switch (requestCode)
        {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if(grantResults.length > 0){
                    for(int i = 0; i < grantResults.length; i++){
                        if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                            mLocationPermssionGranted = false;
                            Log.d(TAG, "onRequestPermissionsResult: Permission Failed!");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: Permission Granted.");
                    mLocationPermssionGranted = true;
                    //Initialize our map
                    initMap();
                }
            }
        }
    }

А вот мой файл AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.triseekapplication">

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

    <application
        android:name="androidx.multidex.MultiDexApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyBdY1ZZdcxDrJG5S_8VPgqDjT57_w-MI30"/>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".CommuterTrafficRulesActivity"></activity>
        <activity android:name=".CommuterProfileActivity" />
        <activity android:name=".CommuterBookRideActivity" />
        <activity android:name=".CommuterTravelHistoryActivity" />
        <activity android:name=".CommuterHomeActivity" />
        <activity android:name=".CommuterActivity" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...