标题说全部,即时使用:
public int onStartCommand(Intent get,int num1,int num2){
if (lm != null){
lm.removeUpdates(this);
}
prefs = getSharedPreferences("Prefs",
Context.MODE_PRIVATE);
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_COARSE );
String provider = lm.getBestProvider( criteria, false );
////* Just GPS is Listed in this List , Google Location is Enabled but Not Detected
/*and Note the Parameter 'false' to get the list of all avaible provider,enable or not
Toast.makeText(this, provider, Toast.LENGTH_LONG).show(); */
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, this);
if(IsFromWidget != true){
str2 = get.getStringExtra("num");
}
CheckNetworkState();
return 0;
}
public void onDestroy()
{
super.onDestroy();
if (lm != null){
lm.removeUpdates(this);
}
}
private void CheckNetworkState() {
if (lm != null){
lm.removeUpdates(this);
}
stopSelf();
}
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
lat = arg0.getLatitude();
lon = arg0.getLongitude();
if (lat == 0 && lon == 0){
}
}
}
if(IsFromWidget = true){
if (lat == 0 && lon == 0){
}
}
stopSelf();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
但它只返回GPS和我的谷歌位置设置已启用,并且我已连接3G或Wifi,它在我使用Android 2.3.x时工作正常,请不要注意代码错误,我在发布之前编辑了代码在这里。
谢谢。
答案 0 :(得分:3)
请记住在AndroidManifest.xml中设置权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
答案 1 :(得分:1)
如果您想找到您的位置,您可以这样做:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
provider = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(provider);
并设置LocationListener类
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc){
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
至少对你来说这是个好开始。祝你好运!