无法在android studio上获得经纬度

时间:2017-04-08 19:29:33

标签: java android android-gps

我正在Android Studio App上工作,想要检索设备的纬度和经度,以便将其发送到Web服务并使用它做一些逻辑。问题是我似乎无法获得经度和经度。这是我的代码:

所有这些都在我的启动器活动的onCreate()方法中,所以它在应用程序启动时运行:

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            TextView coords = (TextView) findViewById(R.id.coords);
            coords.setText("Suas coordenadas: " + location.getLatitude() + ", " + location.getLongitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    };
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if ((checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.INTERNET
            }, 10);
        } else {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.INTERNET
            }, 10);
        }
    } else {
        locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);

当我调试应用程序时,会发生这种情况:

它创建了两个位置管理器和监听器, 将build.versions检查为true(SDK_INT为23,M为23) 当它检查权限时,它会匆忙进入请求权限的else语句

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
            }
            return;
    }
}

此处代码将requestCode作为10,并运行requestLocationUpdates。

直到那里没有错误,但我调试了" OnLocationChanged"在LocationListener中,但应用程序永远不会到达那里并且不会更新coords TextView。

我做错了什么?

的信息: 的build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "vehicleassistant.com.br.vehicleassistant"
        minSdkVersion 19
        targetSdkVersion 14
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.google.android.gms:play-services-ads:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.gms:google-services:3.0.0'
    compile 'com.android.support:support-v4:24.2.1'
    testCompile 'junit:junit:4.12'
}

我在较低版本上运行minSDK版本,因为这是一个生产应用程序,而不是学习/教程应用程序,我想获得尽可能多的设备。 任何帮助表示赞赏,提前谢谢!

根据要求提供清单权限:

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

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

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

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

和整个OnCreate()方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Salvando contexto da aplicação no singleton para ser visto e usado por toda a aplicação
        Singleton.ContextMainActivity = getApplicationContext();
        //Inicializando banco local com dados de cidade baixadas
        try {
            Singleton.bancoCidadesBaixadas = new BancoCidadesBaixadas(Singleton.ContextMainActivity);
            Singleton.bancoCidadesBaixadas.onCreate(Singleton.bancoCidadesBaixadas.getWritableDatabase());
            Toast.makeText(this, "Banco criado", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "Banco não criado: " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        //Inicializando e pedindo permissão do usuario para utilizar serviços de GPS para pegar localização.
        // Caso o GPS esteja desligado, o usuario é redirecionado para a tela de configurações para habilitá-lo.
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                TextView coords = (TextView) findViewById(R.id.coords);
                coords.setText("Suas coordenadas: " + location.getLatitude() + ", " + location.getLongitude());
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.INTERNET
                }, 10);
            } else {
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.INTERNET
                }, 10);
            }
        } else {
            locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        loadingBar = (ProgressBar) findViewById(R.id.loadingBar);
        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.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        itemGroup = navigationView.getMenu().getItem(0).getSubMenu();
        itemSubmenu0 = itemGroup.getItem(0);
        itemSubmenu1 = itemGroup.getItem(1);
//        itemSubmenu2 = itemGroup.getItem(2);
        itemMenu1 = navigationView.getMenu().getItem(1);
        itemMenu2 = navigationView.getMenu().getItem(2);
        itemSubmenu0.setChecked(true);
        //getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new MapsFragment()).commit();

        fragmentManager = getSupportFragmentManager();

        /*Inicia uma transação para conseguir adicionar um fragment na activity
        * Coment. Alex Sousa*/
        showFragment(new MainFragment(), "Inicio");
    }

0 个答案:

没有答案