2010-12-07 87 views
1

我试图大量使用Location API。我没有任何问题做一个简单的活动刷新一个位置监听器的TextView,没关系。安卓位置和主题

事情是,我必须把所有的位置的东西放在像主要活动调用的经理类的东西。所以我必须把所有的东西都放在那个班级里,并且把这个地点告诉活动。这是活动时间:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);   
    setContentView(R.layout.main); 
    g = new GPSManager(getApplicationContext()); 
    t = new Thread(g); 
    t.start(); 
    updateWithNewLocation(g.getLocation()); 
}  
private void updateWithNewLocation(Location location) { 
    String latLongString; 
    TextView myLocationText; 
    myLocationText = (TextView)findViewById(R.id.loca); 
    if (location != null) { 
     double lat = location.getLatitude(); 
     double lng = location.getLongitude(); 
     latLongString = "Lat:" + lat + "\nLong:" + lng; 
    } else { 
     latLongString = "No location found"; 
    } 
    myLocationText.setText("Your Current Position is:\n" + 
    latLongString); 
}  

这是“经理人”类:

public GPSManager(Context context) { 
    locationManager = (LocationManager)context.getSystemService(service); 
    String service = Context.LOCATION_SERVICE; 
    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_LOW); 
    provider = locationManager.getBestProvider(criteria, true); 
} 
public Location getLocation() { 
    return this.location; 
} 
private final LocationListener locationListener = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     Manager.this.location=location; 
    } 
    public void onProviderDisabled(String provider){ 
     locationManager.removeUpdates(this); 
    } 
    public void onProviderEnabled(String provider){ } 
    public void onStatusChanged(String provider, int status, 
     Bundle extras){ } 
    }; 

@Override 
public void run() { 
    Looper.prepare(); 
    locationManager.requestLocationUpdates(provider, 0, 0, 
      locationListener);   
    location = locationManager.getLastKnownLocation(provider); 
    Looper.loop(); 
    Looper.myLooper().quit(); 
} 
private Handler handler = new Handler() { 
@Override 
public void handleMessage(Message msg) { 
    locationManager.removeUpdates(locationListener); 
} 

我的问题是,好了,它不会在所有工作!如果我把这个代码放在活动中,不涉及任何线程,它很好用。但这样,它只是说“找不到位置”。我需要让Manager类始终监听更改,所以当我询问当前位置是否更新时。

回答

0

选项#1:删除“经理”类。

选项2:使“经理”级别为Service

选项#3:将“经理”类设为自定义Application

选项#4:用HandlerThread替换Thread

+0

感谢您的回答!删除管理员类绝对不是一种选择,但它既不是一个服务也不是一个应用程序,所以使它成为一个HandlerThread将是最好的解决方案。问题是,我找不到有关如何实现它的任何信息。你能给我一个额外的手吗?谢谢:) – ferostar 2010-12-07 15:07:53