【问题标题】:I am not getting last location in android我没有在android中获得最后一个位置
【发布时间】:2016-03-05 03:51:26
【问题描述】:

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

Gradle 依赖项:

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>

MainActivity 代码

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();
    }
}

【问题讨论】:

标签: android


【解决方案1】:

使用 Android Marshmallow,您必须明确向用户请求权限,尽管您已在 Manifest 文件中指定了这些权限。 因此,您必须以这种方式请求位置权限: 首先,您为位置创建一个请求代码

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);
                    }

您可以请求Manifest.permission.ACCESS_FINE_LOCATIONManifest.permission.ACCESS_COARSE_LOCATION 或两者。这取决于您的要求。

【讨论】:

  • 感谢沙达布。但它不工作。我已附上日志。希望对您有所帮助。
  • 您是否查看了要求接受/拒绝位置权限的权限弹出窗口?
  • 如果他的目标 SDK 不是 23 或更高版本,这不是问题。较旧的目标不需要它来实现兼容性。问题是 getLastLocation 可以合法地返回 null。
  • 非常感谢 Saeed 和 Shadab 以及所有给我更好的内心的人..你是伟大的兄弟!你解决了问题。它给了我一个弹出窗口,选择后显示我的位置:)
  • @GabeSechan 既然 Deepak nigam 已经接受了我的回答,您愿意回复您的反对票吗?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    从我遇到的这个链接尝试我也放了一些代码,所以你可以试试 Get Current Location 0 in marshmallow where below 23 API its give exact current Location using fused Location

    检查您在其中测试应用的设备是否已更新 google Play 服务??如果没有,则更新它应该与您的 gradle play 服务版本匹配

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-30
      • 2016-03-18
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多