在Android Studio应用中获取当前位置 [英] Getting current location in Android Studio app

查看:899
本文介绍了在Android Studio应用中获取当前位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发我的第一个Android应用程序,它应该获得android设备的纬度经度,并通过Web服务将其发送到模板文档。



我按照从 http://developer.android.com/training/location/retrieve-current.html



这是我的.java类中的代码:

  import android.content.Context; 
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.location.Location;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.provider.Settings;
导入android.support.v7.app.AlertDialog;
导入android.support.v7.app.AppCompatActivity;
导入android.view.View;
导入android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class GetLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
EditText textLat;
EditText textLong;
EditText lat;
EditText lon;

保护无效onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.get_location);

textLat =(EditText)findViewById(R.id.latitude);
textLong =(EditText)findViewById(R.id.longitude);

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
。建立();
}

private boolean isGPSEnabled(){
LocationManager cm =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
返回cm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

@Override
public void onConnected(Bundle bundle){
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation!= null){
lat.setText(String.valueOf(mLastLocation.getLatitude()));
lon.setText(String.valueOf(mLastLocation.getLongitude()));



@Override
public void onConnectionSuspended(int i){

}

@覆盖
public void onConnectionFailed(ConnectionResult connectionResult){

}

public void onButtonClick(View v){
if(v.getId()= =.Rid.getGpsLocation){
if(!isGPSEnabled()){
新AlertDialog.Builder(this)
.setMessage(请激活您的GPS定位!)
.setCancelable(false)
.setPositiveButton(Settings,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int id){
Intent i = new Intent(Settings .ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
})
。 setNegativeButton(Cancel,null)
.show();
} else {
textLat.setText(String.valueOf(lat));
textLong.setText(String.valueOf(lon));
}

}
}


}

我没有得到任何错误,但是当我点击应该获取坐标的按钮时,我在两个视图中都会获得'null'文本 p>

我还包含了互联网的权限,访问精细和粗略的位置。

解决方案

您需要定义LocationListener。

  public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
保护上下文上下文;
TextView txtLat;
字符串拉特;
字符串提供程序;
保护字符串纬度,经度;
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat =(TextView)findViewById(R.id.textview1);

locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
}
@Override
public void onLocationChanged(Location location){
txtLat =(TextView)findViewById(R.id.textview1);
txtLat.setText(Latitude:+ location.getLatitude()+,Longitude:+ location.getLongitude());
}

@Override
public void onProviderDisabled(String provider){
Log.d(Latitude,disable);
}

@Override
public void onProviderEnabled(String provider){
Log.d(Latitude,enable);

$ b @Override
public void onStatusChanged(String provider,int status,Bundle extras){
Log.d(Latitude,status);
}
}

并且需要给予以下权限:



ACCESS_COARSE_LOCATION :当我们为我们的Android应用程序使用网络位置提供程序时,会使用它。 强> ACCESS_FINE_LOCATION :它为这两个提供商提供许可。


$ b 互联网:权限是必须为网络提供商使用。

I am developing my first Android app which should get the latitude and longitude of an android device and send it via a web service to a template document.

I followed the guide of getting the location from http://developer.android.com/training/location/retrieve-current.html.

This is the code from my .java class:

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class GetLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;
    EditText textLat;
    EditText textLong;
    EditText lat;
    EditText lon;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_location);

        textLat = (EditText) findViewById(R.id.latitude);
        textLong = (EditText) findViewById(R.id.longitude);

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

    private boolean isGPSEnabled() {
        LocationManager cm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return cm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            lat.setText(String.valueOf(mLastLocation.getLatitude()));
            lon.setText(String.valueOf(mLastLocation.getLongitude()));
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public void onButtonClick(View v){
        if(v.getId() == R.id.getGpsLocation){
            if(!isGPSEnabled()){
                new AlertDialog.Builder(this)
                        .setMessage("Please activate your GPS Location!")
                        .setCancelable(false)
                        .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(i);
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .show();
            } else {
                textLat.setText(String.valueOf(lat));
                textLong.setText(String.valueOf(lon));
            }

        }
    }


}

I don't get any errors but when I am tapping the button which should get the coordinates, I get 'null' text in both views.

I also have included permissions for internet, access fine and coarse location.

Thanks in advance!

解决方案

You need to define LocationListener .

public class MainActivity extends Activity implements LocationListener{
    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;
    TextView txtLat;
    String lat;
    String provider;
    protected String latitude,longitude; 
    protected boolean gps_enabled,network_enabled;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtLat = (TextView) findViewById(R.id.textview1);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    @Override
    public void onLocationChanged(Location location) {
        txtLat = (TextView) findViewById(R.id.textview1);
        txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Latitude","disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Latitude","enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Latitude","status");
    }
}

And need to give below permission :

ACCESS_COARSE_LOCATION : It is used when we use network location provider for our Android app.

ACCESS_FINE_LOCATION : It is providing permission for both providers.

INTERNET : permission is must for the use of network provider.

这篇关于在Android Studio应用中获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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