当前位置: 首页 > 知识库问答 >
问题:

我不会在Android上找到最后一个位置

柳向明
2023-03-14

我正在学习Android Google API。我正在创建一个应用程序以通过Google Play服务获取最后一个位置。在尝试了许多教程后,我的位置变得为空。我正在我的手机上运行应用程序,即API 23。我在手机上保留位置和数据设置。下面是我的代码。

渐变相关性:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:7.5.0'
}

AndroidManifest。xml

<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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


</application>

主活动代码

package com.lab.locationawareapp;

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;


public class MainActivity extends AppCompatActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {

    protected static final String TAG = "MainActivity";

    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mGoogleApiClient;

    /**
     * Represents a geographical location.
     */
    protected Location mLastLocation;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;



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

        mLatitudeLabel = getResources().getString(R.string.latitude_label);
        mLongitudeLabel = getResources().getString(R.string.longitude_label);
        mLatitudeText = (TextView) findViewById((R.id.latitude_text));
        mLongitudeText = (TextView) findViewById((R.id.longitude_text));

        buildGoogleApiClient();
    }

    /**
     * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Runs when a GoogleApiClient object successfully connects.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
                    mLastLocation.getLatitude()));
            mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
                    mLastLocation.getLongitude()));
        } else {
            Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {

        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
}

共有3个答案

和斌
2023-03-14

试着从我面对的这个链接,我在那里放了一些代码,所以你可以试着得到Marshmallow中的当前位置0,低于23 API,使用融合位置给出确切的当前位置

检查您测试应用程序的设备是否更新了google Play服务??如果没有,那么更新它应该与你的gradle play服务版本相匹配

陆文博
2023-03-14

如果系统没有缓存的位置,getLast位置将返回null。这是指其他程序最近没有请求该位置的任何时候。您要么需要检查它是否为空,要么需要请求位置而不是获取最后一个位置(请注意,请求位置需要时间,并且如果您无法获得GPS锁定并且想要高精度,可能永远不会调用您的回调)。

娄飞鸾
2023-03-14

使用AndroidMarshmallow,您必须明确请求用户的许可,尽管您已在清单文件中指定了这些许可。因此,您必须通过以下方式请求位置权限:首先,您为位置创建一个请求代码

public static final int LOCATION_REQUEST_CODE = 1001; //Any number

然后检查是否已经授予权限,如果没有,代码将请求权限,这将显示一个本机弹出窗口,要求拒绝/允许位置权限

if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
        } else {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }

在请求任何位置之前,最好在活动的onCreate()中写入上述代码。然后根据用户在弹出窗口上采取的操作,您将得到一个回调,您可以根据自己的需求执行。

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LOCATION_REQUEST_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                   mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                }
            }
        }
    }

此外,无论您在哪里尝试获取位置,都应该检查是否已向应用程序授予位置权限,然后获取位置。

 if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                          mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    }

您可以请求清单。准许访问\u FINE\u位置清单。准许访问\u粗略\u位置,或同时访问两者。这取决于你的要求。

 类似资料:
  • 问题内容: 我想支持Rtl,并在最后一个片段上设置当前项目,但是当我在自己的代码中编写此代码时,我不知道如何访问最后一个片段。 根据这篇文章,我想让我成为Rtl: MainActivity.java ,我在其中定义: 最后,这是我的视图寻呼机适配器: 问题答案: 因为我用: 在设置适配器之前,它无法正常工作,在设置适配器之后,我应该编写此代码,这要归功于Kevin Chris和K Neeraj L

  • 问题内容: 下面的代码是在第一个位置上查找视图。如何找到最后一个位置的视图? 这是我的xml 问题答案: 试试这个 试试这个 或尝试这个 只需执行以下操作即可:

  • 问题内容: 我想知道用JPA获取表的最后一个条目的最佳方法是什么。在Sql中,我正在寻找的将是: 我当时在考虑model.count(),但这听起来更像是一种破解,而不是一个好的解决方案;) 问题答案: 您可以使用看起来与查询非常相似的。 建立后,您可以致电 其次是 编辑:我的错误:请注意下面的mtpettyp的注释。 不要使用query.getSingleResult(),因为如果返回的行不完全

  • 我正在尝试运行我的React-native应用程序“Android”,但在我手动添加项目文件中的SDK路径之前,每次都是这样 local.properties RN错误 那我犯了什么错?

  • 问题内容: 我有一个android项目,在其中使用本机代码对SIP进行处理(使用libosip2和libeXosip2)。我的本机代码与库的源代码一起编译到一个模块中。 代码可以正常编译,并且生成的库具有我期望的所有符号,但是当我尝试加载生成的库时,出现以下错误: 我的Application.mk看起来像这样: 我确实使用ndk-depends检查了未捕获的依赖项,这给了我 添加loadLibra