Java 如何以编程方式获取android中的当前位置?

Java 如何以编程方式获取android中的当前位置?,java,android,android-manifest,Java,Android,Android Manifest,我正在尝试在android上制作一个简单的应用程序,使用GPS或网络提供商(WIFI或tower)获取当前位置,但我在尝试在android上运行时遇到了很多问题。它不会启动它给了我一个例外,我不知道为什么 这是代码。这很简单,因为我想测试获取位置&稍后我将添加一些特性和功能 主要问题: package com.GpsTesting; import android.app.Activity; import android.content.Context; import android.locat

我正在尝试在android上制作一个简单的应用程序,使用GPS或网络提供商(WIFI或tower)获取当前位置,但我在尝试在android上运行时遇到了很多问题。它不会启动它给了我一个例外,我不知道为什么

这是代码。这很简单,因为我想测试获取位置&稍后我将添加一些特性和功能

主要问题:

package com.GpsTesting;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class GPS_TestActivity extends Activity{
    /** Called when the activity is first created. */
    String location_text="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

     // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
              // Called when a new location is found by the network location provider.

                if (location != null) {
                    double lat = location.getLatitude();
                    double lng = location.getLongitude();

                    location_text= "latitude: "+lat+"longitude: "+lng;

                    Toast.makeText(getApplicationContext(), location_text, Toast.LENGTH_SHORT).show();

                }
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}
          };



        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);

    }

}
舱单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.GpsTesting"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:permission="android.permission.ACCESS_FINE_LOCATION">
        <activity android:name=".GPS_TestActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />


</manifest>

那么,代码中有问题吗??我正在使用在线教程(来自android开发和其他网站)来完成这项工作

非常感谢

添加注释:

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(lm==null)
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gps_enabled && !network_enabled)
        return false;

    if(gps_enabled)
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,  locationListenerGps);
    if(network_enabled)
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,  locationListenerNetwork);
    timer1=new Timer();
    timer1.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
         lm.removeUpdates(locationListenerGps);
         lm.removeUpdates(locationListenerNetwork);

         Location net_loc=null, gps_loc=null;
         if(gps_enabled)
             gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
         if(network_enabled)
             net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

         //if there are both values use the latest one
         if(gps_loc!=null && net_loc!=null){
             if(gps_loc.getTime()>net_loc.getTime())
                 locationResult.gotLocation(gps_loc);
             else
                 locationResult.gotLocation(net_loc);
             return;
         }

         if(gps_loc!=null){
             locationResult.gotLocation(gps_loc);
             return;
         }
         if(net_loc!=null){
             locationResult.gotLocation(net_loc);
             return;
         }
         locationResult.gotLocation(null);
    }
}

public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
}
}


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
**我真的厌倦了这件事。我尝试使用eclipse方式运行应用程序(通过USB连接我的设备&将应用程序运行到设备而不是应用程序中)。。 当我尝试这种方法时,应用程序运行良好,没有问题!!!使用旧方法时(通过电子邮件发送.apk,然后从手机安装,它总是给我一个例外!!) 谁能为我解释一下为什么会发生这种事??我错过了什么吗?? 从那时起,我就知道安卓系统的开发。所以,我恐怕我漏掉了一点

注: 我正在通过电子邮件发送bin文件夹中的.apk文件(出于测试目的,使用eclipse签名)。。。我尝试使用另一个简单的应用程序,只是为了确保bin文件夹中可用的.apk文件是否正确(用于测试)&它确实有效。。所以,apk文件很好。。。但是为什么网络应用程序在eclipse中不起作用,而它却起作用呢?? 提前感谢;)**

已解决;)

我之前在应用程序标记的清单中添加了权限的问题解决方案

android:permission=“android.permission.ACCESS\u FINE\u位置”

而且它是重复的,因为它已经被添加到下面(或者因为它在错误的地方)。 因此,我删除了它&它运行良好


非常感谢各位

您的清单中可能缺少internet权限

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

我想你可以阅读和观看Reito Meier在IO 2011期间提供的内容

Meier的Google IO 2011(观看视频、获取幻灯片、获取代码片段……):

Reito Meier关于基于位置的应用程序的出版物:


首先,我检查启用了哪些提供程序。有些可能在设备上被禁用,有些可能在应用程序清单中被禁用。 如果有任何提供程序可用,我将启动位置侦听器和超时计时器。在我的例子中是20秒,对于GPS来说可能不够,所以你可以放大它。 如果我从位置侦听器获得更新,我将使用提供的值。我停止听众和计时器。 如果我没有得到任何更新,并且计时器超时,我必须使用最后的已知值。 我从可用的提供者那里获取最后的已知值,并选择最近的值

   MyLocation myLocation = new MyLocation();

   private void locationClick() {
    myLocation.getLocation(this, locationResult);
   }

public LocationResult locationResult = new LocationResult() {

    @Override
    public void gotLocation(final Location location) {
        //Got the location!
    }
};
这是MyLocation类:

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(lm==null)
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gps_enabled && !network_enabled)
        return false;

    if(gps_enabled)
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,  locationListenerGps);
    if(network_enabled)
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,  locationListenerNetwork);
    timer1=new Timer();
    timer1.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer1.cancel();
        locationResult.gotLocation(location);
        lm.removeUpdates(this);
        lm.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
         lm.removeUpdates(locationListenerGps);
         lm.removeUpdates(locationListenerNetwork);

         Location net_loc=null, gps_loc=null;
         if(gps_enabled)
             gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
         if(network_enabled)
             net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

         //if there are both values use the latest one
         if(gps_loc!=null && net_loc!=null){
             if(gps_loc.getTime()>net_loc.getTime())
                 locationResult.gotLocation(gps_loc);
             else
                 locationResult.gotLocation(net_loc);
             return;
         }

         if(gps_loc!=null){
             locationResult.gotLocation(gps_loc);
             return;
         }
         if(net_loc!=null){
             locationResult.gotLocation(net_loc);
             return;
         }
         locationResult.gotLocation(null);
    }
}

public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
}
}


<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
import java.util.Timer;
导入java.util.TimerTask;
导入android.content.Context;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;
公共类位置{
定时器1;
位置经理lm;
定位结果定位结果;
布尔值gps_enabled=false;
布尔网络_enabled=false;
公共布尔getLocation(上下文、LocationResult)
{
//我使用LocationResult回调类将位置值从MyLocation传递给用户代码。
位置结果=结果;
如果(lm==null)
lm=(LocationManager)context.getSystemService(context.LOCATION\u服务);
//如果不允许提供程序,将引发异常。
请尝试{gps_enabled=lm.isProviderEnabled(LocationManager.gps_PROVIDER);}catch(异常示例){}
请尝试{network_enabled=lm.isProviderEnabled(LocationManager.network_PROVIDER);}catch(Exception ex){}
//如果未启用任何提供程序,则不要启动侦听器
如果(!gps_已启用&&!网络_已启用)
返回false;
如果(gps_已启用)
lm.RequestLocationUpdate(LocationManager.GPS_提供程序,0,0,locationListenerGps);
如果(网络已启用)
lm.RequestLocationUpdate(LocationManager.NETWORK\u提供程序,0,0,locationListenerNetwork);
timer1=新定时器();
timer1.schedule(新GetLastLocation(),20000);
返回true;
}
LocationListener locationListenerGps=新LocationListener(){
已更改位置上的公共无效(位置){
timer1.cancel();
locationResult.gotLocation(位置);
lm.移除更新(本);
lm.RemoveUpdate(locationListenerNetwork);
}
公共无效onProviderDisabled(字符串提供程序){}
公共无效onProviderEnabled(字符串提供程序){}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){}
};
LocationListener locationListenerNetwork=新LocationListener(){
已更改位置上的公共无效(位置){
timer1.cancel();
locationResult.gotLocation(位置);
lm.移除更新(本);
lm.移除更新(locationListenerGps);
}
公共无效onProviderDisabled(字符串提供程序){}
公共无效onProviderEnabled(字符串提供程序){}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){}
};
类GetLastLocation扩展了TimerTask{
@凌驾
公开募捐{
lm.移除更新(locationListenerGps);
lm.RemoveUpdate(locationListenerNetwork);
位置网位置=零,gps位置=零;
如果(gps_已启用)
gps_loc=lm.getLastKnownLocation(LocationManager.gps_PROVIDER);
如果(网络已启用)
net_loc=lm.getlastnownlocation(LocationManager.NETWORK_PROVIDER);
//如果两个值都存在,则使用最新的值
如果(gps_-loc!=null&&net_-loc!=null){
如果(全球定位系统位置g