Prince OfThief
Prince OfThief

Reputation: 6423

Android : How to location the application?

How to get the current location using IP Address?

Upvotes: 0

Views: 408

Answers (3)

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,

Upvotes: 0

Varun
Varun

Reputation: 33983

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

Upvotes: 0

Joakim Berglund
Joakim Berglund

Reputation: 2871

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.

Upvotes: 1

Related Questions