如何使用GPS在Android中获取当前位置? [英] How can I get my current location in Android using GPS?

查看:113
本文介绍了如何使用GPS在Android中获取当前位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过GPS以地址的形式获取当前位置.我正在使用android studio. 就是说我的应用程序停止工作. 有什么错误吗? 有人可以帮我摆脱困境吗?

I want to get my current location in the form of an address by GPS. I am using the android studio. It is saying that my application stops working. What is the error in it? Can someone help me to get out of this, please?

activity_main.xml文件中的我的代码为

My Code in activity_main.xml file is

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我在MainActivity.java中的代码是

My code in MainActivity.java is

package com.example.showlatlong;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

Location gps_loc, network_loc, final_loc;
double longitude;
double latitude;
String userCountry, userAddress;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = findViewById(R.id.text_view);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {

        return;
    }

    try {
        gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (gps_loc != null) {
        final_loc = gps_loc;
        latitude = final_loc.getLatitude();
        longitude = final_loc.getLongitude();
    }
    else if (network_loc != null) {
        final_loc = network_loc;
        latitude = final_loc.getLatitude();
        longitude = final_loc.getLongitude();
    }
    else {
        latitude = 0.0;
        longitude = 0.0;
    }

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



    try {

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null && addresses.size() > 0) {
            userCountry = addresses.get(0).getCountryName();
            userAddress = addresses.get(0).getAddressLine(0);
            tv.setText(userCountry + ", " + userAddress);
        }
        else {
            userCountry = "Unknown";
            tv.setText(userCountry);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

我在manifest.xml中的代码是

My code in manifest.xml is

<?xml version="1.0" encoding="utf-8"?>

<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: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">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

整个代码是这个.它正在打开该应用程序,并且不到一秒钟,它就在我的android应用程序上抛出一条错误消息应用程序不断停止",从而关闭了该应用程序. 这就是我在logcat中得到的

The entire code is this. It is opening the app and in less than a second, it is closing by throwing an error message that "app keeps stopping" on my android application. This is what I got in the logcat is

2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.showlatlong, PID: 15400
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.showlatlong/com.example.showlatlong.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6238)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
 Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
 Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.constraint.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.showlatlong-1/base.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.showlatlong-1/lib/arm64, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.view.LayoutInflater.createView(LayoutInflater.java:613)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:812)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:499)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:430)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
    at com.example.showlatlong.MainActivity.onCreate(MainActivity.java:29)
    at android.app.Activity.performCreate(Activity.java:6857)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6238)
    at java.lang.reflect.Method.invoke(Native Method)
    at 


 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit. 
 java:933)
 2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong  
 E/AndroidRuntime:     
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

推荐答案

在AndroidManifest.xml中,您必须将其放在应用程序标签的上方或下方.

In your AndroidManifest.xml, you have to put this above or below the application tag.

<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"/>

因为您没有显示代码在做什么,所以我不知道如何解决您的问题.但是下面的代码是我在应用程序中用来获取当前用户所在国家/地区的代码.

Because you did not show your code what you have been doing, so I have no clue how to resolve your problems. But the below code is the code I use for my application to get the current country of users.

activity_main.xml

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

MainActivity.java

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

        Location gps_loc;
        Location network_loc;
        Location final_loc;
        double longitude;
        double latitude;
        String userCountry, userAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        TextView tv = findViewById(R.id.text_view);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

        try {

            gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gps_loc != null) {
            final_loc = gps_loc;
            latitude = final_loc.getLatitude();
            longitude = final_loc.getLongitude();
        }
        else if (network_loc != null) {
            final_loc = network_loc;
            latitude = final_loc.getLatitude();
            longitude = final_loc.getLongitude();
        }
        else {
            latitude = 0.0;
            longitude = 0.0;
        }


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

        try {

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null && addresses.size() > 0) {
                userCountry = addresses.get(0).getCountryName();
                userAddress = addresses.get(0).getAddressLine(0);
                tv.setText(userCountry + ", " + userAddress);
            }
            else {
                userCountry = "Unknown";
                tv.setText(userCountry);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

您将必须 理解此代码 .还有一件事,如果您在模拟器上运行应用程序,它将继续显示美国"或更具体地说Googleplex的位置.只需在真实的设备上运行它,即可使其返回您的当前位置.

You will have to understand this code. One more thing, if you run your application on an emulator, it will keep showing "United States" or more specifically, Googleplex's location. Just run it on a real device to make it return your current location.

要返回当前位置,而不仅仅是国家/地区本身,可以替换

To return your current location other than just country itself, you can replace the

addresses.get(0).getCountryName()

addresses.get(0).getCountryName()

类似

addresses.get(0).getPostalCode()

addresses.get(0).getPostalCode()

addresses.get(0).getAdminArea()

addresses.get(0).getAdminArea()

以此类推.

您也可以将值串联为字符串以详细显示当前位置.

You can too concatenate the values as a string to show your current location in detail.

请查看

这篇关于如何使用GPS在Android中获取当前位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆