查找用户位置 [英] Finding user location

查看:95
本文介绍了查找用户位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的天气应用获取用户位置信息。我目前无法这样做,并试图关注Google最新的位置指南,以及 https://guides.codepath.com/android/Retrieving-Location-with-LocationServices-API

  import android.Manifest; 
导入android.content.Context;
导入android.content.pm.PackageManager;
导入android.graphics.drawable.Drawable;
导入android.location.Location;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.Bundle;
导入android.support.annotation.NonNull;
导入android.support.annotation.Nullable;
导入android.support.v4.app.ActivityCompat;
导入android.support.v7.app.AppCompatActivity;
导入android.util.Log;
导入android.view.View;
导入android.widget.ImageView;
导入android.widget.ProgressBar;
导入android.widget.TextView;
导入android.widget.Toast;

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

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

导入butterknife.BindView;
导入butterknife.ButterKnife;
导入okhttp3.Call;
导入okhttp3.Callback;
导入okhttp3.OkHttpClient;
导入okhttp3.Request;
导入okhttp3.Response;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {

public static final String TAG = MainActivity.class.getSimpleName();

Public CurrentWeather mCurrentWeather;

私有GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

双纬度;
双经度;

@BindView(R.id.timeLabel)
TextView mTimeLabel;
@BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
@BindView(R.id.humidityValue)
TextView mHumidityValue;
@BindView(R.id.precipValue)
TextView mPrecipValue;
@BindView(R.id.summaryTextView)
TextView mSummaryLabel;
@BindView(R.id.iconImageView)
ImageView mIconImageView;
@BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
@BindView(R.id.progressBar)
ProgressBar mProgressBar;

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

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build() ;

//导入视图变量
ButterKnife.bind(this);

//将默认进度条设置为不可见
mProgressBar.setVisibility(View.INVISIBLE);

//为刷新按钮创建onClick
mRefreshImageView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
getForecast(经度,纬度);
}
});

getForecast(经度,纬度);


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

$ b @覆盖
保护无效onStop(){
if(mGoogleApiClient!= null){
mGoogleApiClient.disconnect();
}
super.onStop();
}

@Override
public void onConnected(@Nullable Bundle bundle){

if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION )!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
// TODO:考虑调用
// ActivityCompat#requestPermissions
//在这里请求丢失的权限,然后覆盖
// public void onRequestPermissionsResult(int requestCode,String [] permissions,
// int [] grantResults)
// to处理用户授予权限的情况。有关更多详细信息,请参阅文档
//获取ActivityCompat#requestPermissions。
return;
}
位置mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mCurrentLocation!= null){
Log.d(DEBUG,current location:+ mCurrentLocation.toString());
latitude = mCurrentLocation.getLatitude();
longitude = mCurrentLocation.getLongitude();
}
}

@Override
public void onConnectionSuspended(int i){
if(i == CAUSE_SERVICE_DISCONNECTED){
Toast。 makeText(this,Disconnected。Please re-connect。,Toast.LENGTH_SHORT).show();
} else if(i == CAUSE_NETWORK_LOST){
Toast.makeText(this,Network lost。Please re-connect。,Toast.LENGTH_SHORT).show();
}
}

我想要实现的是获得lat和长坐标,然后将它们保存到全局变量中,以便在调用 getForecast()时使用。



AndroidManifest.xml:

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

<使用权限android:name =android.permission.INTERNET/>
< uses-permission android:name =android.permission.ACCESS_NETWORK_STATE/>
< uses-permission android:name =android.permission.ACCESS_COARSE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>

< application
android:allowBackup =true
android:icon =@ mipmap / ic_launcher
android:label =@ string / app_name
android:supportsRtl =true
android:theme =@ style / AppTheme>
< activity android:name =。MainActivity
android:screenOrientation =portrait>
< intent-filter>

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

< / manifest>


解决方案

请尝试以下解决方案:


  • 首先,确保您在活动类中实现了正确的LocationListener接口:

      com.google.android.gms.location.LocationListener 




然后请求适当的权限以支持运行 v6.0

  private static final int MY_PERMISSION_REQUEST_READ_COARSE_LOCATION = 102; 

然后请求权限:

  @Override 
public void onConnected(@Nullable Bundle bundle){

//您使用的是什么版本的Android?
// Answer = 6.0

if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(thisActivity,
new String [] {Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_REQUEST_READ_COARSE_LOCATION);

}

位置mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mCurrentLocation!= null){
Log.d(TAG,当前位置:+ mCurrentLocation.toString());
latitude = mCurrentLocation.getLatitude();
longitude = mCurrentLocation.getLongitude();
}

startLocationUpdates();






要在运行时从权限请求获得结果,方法:

$ $ $ $ $ $ $ $ $ $ $ $ $ public void onRequestPermissionsResult(int requestCode,
String permissions [],int [ ] grantResults){
switch(requestCode){

case MY_PERMISSION_REQUEST_READ_COARSE_LOCATION:~~~~~~~~~~~
//如果请求被取消,结果数组是空。
if(grantResults.length> 0
&&& amp; grantResults [0] == PackageManager.PERMISSION_GRANTED){

//授予权限,耶!做你需要做的
//联系人相关的任务。

} else {

// permission denied,boo!禁用依赖此权限的
//功能。
}
break;
}

//其他'case'行检查其他
//权限此应用可能请求
}
}

然后,您的方法更新位置:

  protected void startLocationUpdates(){
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval( FASTEST_INTERVAL);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){

//在这里请求权限已经在
return之上;
}

//这里存在问题,因为LocationListener被强制转换为活动
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}

这应该做到这一点;

快乐编码!

I am trying to get user location for my weather app. I am currently unable to do so and have tried to follow both the Google Last known location guide, as well as https://guides.codepath.com/android/Retrieving-Location-with-LocationServices-API.

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
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.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public static final String TAG = MainActivity.class.getSimpleName();

    public CurrentWeather mCurrentWeather;

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    double latitude;
    double longitude;

    @BindView(R.id.timeLabel)
    TextView mTimeLabel;
    @BindView(R.id.temperatureLabel)
    TextView mTemperatureLabel;
    @BindView(R.id.humidityValue)
    TextView mHumidityValue;
    @BindView(R.id.precipValue)
    TextView mPrecipValue;
    @BindView(R.id.summaryTextView)
    TextView mSummaryLabel;
    @BindView(R.id.iconImageView)
    ImageView mIconImageView;
    @BindView(R.id.refreshImageView)
    ImageView mRefreshImageView;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();

        // Import view variables
        ButterKnife.bind(this);

        // Set default progressbar to invisible 
        mProgressBar.setVisibility(View.INVISIBLE);

        // Create onClick for the refresh button
        mRefreshImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getForecast(latitude, longitude);
            }
        });

        getForecast(latitude, longitude);
    }

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

    @Override
    protected void onStop() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mCurrentLocation != null){
            Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
            latitude = mCurrentLocation.getLatitude();
            longitude = mCurrentLocation.getLongitude();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        if (i == CAUSE_SERVICE_DISCONNECTED) {
            Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
        } else if (i == CAUSE_NETWORK_LOST) {
            Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
        }
    }

What I am trying to achieve is to get the lat and long coordinates and then save them to the global variables to later be used when making the call to getForecast().

AndroidManifest.xml:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>

解决方案

Try the following solution:

  • First, make sure you have implemented the correct LocationListener interface in your activity class:

     com.google.android.gms.location.LocationListener
    

Then request the appropriate permissions to support Android devices running v6.0

 private static final int MY_PERMISSION_REQUEST_READ_COARSE_LOCATION = 102;

Then request permission:

@Override
public void onConnected(@Nullable Bundle bundle) {

  // what version of android are you using?
  // Answer = 6.0

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
        ActivityCompat.requestPermissions(thisActivity,
              new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
              MY_PERMISSION_REQUEST_READ_COARSE_LOCATION);

    }

    Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mCurrentLocation != null) {
        Log.d(TAG, "current location: " + mCurrentLocation.toString());
        latitude = mCurrentLocation.getLatitude();
        longitude = mCurrentLocation.getLongitude();
    }

     startLocationUpdates();

}

To get the results from permission requests at runtime, override this method:

@Override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {
    switch (requestCode) {

      case MY_PERMISSION_REQUEST_READ_COARSE_LOCATION:~~~~~~~~~~~
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // permission was granted, yay! Do the
            // contacts-related task you need to do.

        } else {

            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
        break;
    }

    // other 'case' lines to check for other
    // permissions this app might request
  }
}

Then, your method to update location:

protected void startLocationUpdates() {
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        //request permission here like you already do above
        return;
    }

    //there is a problem here because LocationListener is cast as an activity
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

This should do it;

Happy coding!

这篇关于查找用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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