Android:如何定位应用程序?

发布于 2024-10-06 11:56:16 字数 22 浏览 4 评论 0原文

如何使用IP地址获取当前位置?

How to get the current location using IP Address?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

强辩 2024-10-13 11:56:16

主题获取用户位置位于http://developer.android.com 涵盖了使用 Android 中的内置函数获取位置。

它还指出:

网络位置提供商无需使用 GPS 即可提供良好的位置数据。

和:

限制一组提供者

根据应用程序的使用环境或所需的准确度,您可以选择仅使用网络位置提供程序或仅使用 GPS,而不是同时使用两者。仅与其中一项服务交互可减少电池使用量,但可能会降低准确性。

Topic Obtaining user location over at http://developer.android.com covers obtaining location using the inbuilt functions in Android.

It also states this:

The Network Location Provider provides good location data without using GPS.

And:

Restrict a set of providers

Depending on the environment where your application is used or the desired level of accuracy, you might choose to use only the Network Location Provider or only GPS, instead of both. Interacting with only one of the services reduces battery usage at a potential cost of accuracy.

撩动你心 2024-10-13 11:56:16

为什么要使用ip地址来查找位置? IP 地址只能提供包含国家/地区详细信息的位置信息,而且您还依赖于使用 IP 进行地理位置定位的网络服务,该服务不太可靠,并且仅在您可以访问互联网时才起作用。此外,如果您要连接到应用程序中的服务器,那么您可以让服务器执行此操作,这样会快得多。

您的设备上有 GPS,它可以为您提供经纬度的实时用户位置。您可以点击 Joakim 的回答中的链接

Why do you want to use ip address to find the location? IP Adress can give location info with country details only and also you are dependent on a webservice that does the geo location with IP which is less reliable and will work only if you have internet access. Also if you are connecting to a server in your app then you can just let the server do this which will be much faster.

You have GPS on the device which will give you the realtime user location in terms of lat and lon. You can follow the link in Joakim's answer

叹梦 2024-10-13 11:56:16

如果你想获取移动位置,你首先需要一个提供商,在我的例子中,我使用谷歌 API 从你的手机获取 GPS 位置,你需要从 API 获取令牌,在下面的教程中解释了如何获取位置你的手机。

http://blog.teamtreehouse.com/beginners-guide-location-android

如果您有疑问,请从 Android 开发者网站获取。

http://developer.android.com/training/location/retrieve-current.html
http://developer.android.com/training/location/receive-location-updates.html

这对我来说最重要的是,在开发过程中,我必须从片段中获取位置,并且我使用片段来获取任何需要我的 Android 应用程序中的位置的活动的位置。

使用回调来请求位置手机。

重要的是你需要位置和其他人的许可才能工作...

<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" />
<!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature android:glEsVersion="0x00020000" android:required="true"/>

活动中的XML必须有片段:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<fragment android:name="es.urjc.mov.javsan.fichas.LocationFragment"
    android:id="@+id/location_fragment"
    android:layout_height="0dip"
    android:layout_weight="0"
    android:layout_width="match_parent" />

</LinearLayout>

片段代码:

package es.urjc.mov.javsan.fichas;

import android.Manifest; 
import android.app.Fragment;
import android.content.IntentSender;
import android.content.pm.PackageManager;  
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; 

import com.google.android.gms.appindexing.AppIndex;
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;

public class LocationFragment extends Fragment  implements
        com.google.android.gms.location.LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = LocationFragment.class.getSimpleName();

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private android.location.Location currentLocation;

private View fragmentLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    fragmentLayout = inflater.inflate(R.layout.location_fragment, container, false);

    buildLocation();
    return fragmentLayout;
}


@Override
public void onStart() {
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
    super.onStart();
}

@Override
public void onResume() {
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
    super.onResume();
}

@Override
public void onStop() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
    super.onStop();
}


@Override
public void onConnected(Bundle bundle) {
    if (isDenyLocation()) {
        requestAllowLocation();
        return;
    }

    android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location != null) {
        handleNewLocation(location);
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.e(TAG, String.format("%s\n", "Connection suspended please reconnect..."));
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.v(TAG, String.format("Connection failed : %s", connectionResult.toString()));

    if (!connectionResult.hasResolution()) {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        return;
    }

    try {
        // Start an Activity that tries to resolve the error
        connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}

private void buildLocation() {

    if (mGoogleApiClient == null) {
        // Create the GoogleApiClient Object.
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(AppIndex.API).build();
    }

    if (mLocationRequest == null) {
        // Create the LocationRequest Object.
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
    }

}

private void handleNewLocation(Location location) {
    currentLocation = location;
    Log.e(TAG, String.format("Current Location : %f, %f",
            currentLocation.getLongitude(), currentLocation.getLatitude()));
}

我希望这有帮助!

哈维,

If you wanna get the mobile location you need first a provider in my case I use google API to get the GPS location from you mobile phone, you need get the token from the API in the follow tutorial explain really good how to get the location from your mobile phone.

http://blog.teamtreehouse.com/beginners-guide-location-android

And from android developer web if you although have doubts.

http://developer.android.com/training/location/retrieve-current.html
http://developer.android.com/training/location/receive-location-updates.html

And this is the most important for me in the develop I got to get the location from a fragment and I use the fragment to get the location in anywhere activity whose need the location in my android application..

Using the callbacks to request the location of the mobile phone.

Important you need permission of location and others to work...

<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" />
<!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature android:glEsVersion="0x00020000" android:required="true"/>

XML in activity must have the fragment :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<fragment android:name="es.urjc.mov.javsan.fichas.LocationFragment"
    android:id="@+id/location_fragment"
    android:layout_height="0dip"
    android:layout_weight="0"
    android:layout_width="match_parent" />

</LinearLayout>

Fragment Code :

package es.urjc.mov.javsan.fichas;

import android.Manifest; 
import android.app.Fragment;
import android.content.IntentSender;
import android.content.pm.PackageManager;  
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; 

import com.google.android.gms.appindexing.AppIndex;
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;

public class LocationFragment extends Fragment  implements
        com.google.android.gms.location.LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

private static final String TAG = LocationFragment.class.getSimpleName();

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private android.location.Location currentLocation;

private View fragmentLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    fragmentLayout = inflater.inflate(R.layout.location_fragment, container, false);

    buildLocation();
    return fragmentLayout;
}


@Override
public void onStart() {
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
    super.onStart();
}

@Override
public void onResume() {
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }
    super.onResume();
}

@Override
public void onStop() {
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
    super.onStop();
}


@Override
public void onConnected(Bundle bundle) {
    if (isDenyLocation()) {
        requestAllowLocation();
        return;
    }

    android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location != null) {
        handleNewLocation(location);
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.e(TAG, String.format("%s\n", "Connection suspended please reconnect..."));
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.v(TAG, String.format("Connection failed : %s", connectionResult.toString()));

    if (!connectionResult.hasResolution()) {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        return;
    }

    try {
        // Start an Activity that tries to resolve the error
        connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}

private void buildLocation() {

    if (mGoogleApiClient == null) {
        // Create the GoogleApiClient Object.
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(AppIndex.API).build();
    }

    if (mLocationRequest == null) {
        // Create the LocationRequest Object.
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
    }

}

private void handleNewLocation(Location location) {
    currentLocation = location;
    Log.e(TAG, String.format("Current Location : %f, %f",
            currentLocation.getLongitude(), currentLocation.getLatitude()));
}

I hope this help!

Javi,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文