0

我正在创建一个从 NETWORK 获取位置的小部件。但onLocationChanged()没有被调用但locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);被执行

每次都会创建新的小部件实例,因此使用了静态。

public class MyWidget extends AppWidgetProvider implements LocationListener {
    private static LocationManager locMgr;
    private static List<String> providers;
    private static String bestProvider;
    private static Double  lat , longt; 

  public void onEnabled(Context context) {
    super.onEnabled(context);

    if(locMgr == null)  {       //Get LocationManager
        locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        getLocations();
    }    

  }

 public void getLocations() {
    //List All providers
    providers = locMgr.getAllProviders();

    //Get criteria
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);

    //Get best provider
    bestProvider = locMgr.getBestProvider(criteria, false);       

    //Get Last known location
    //String locationProvider = LocationManager.GPS_PROVIDER;
    try {
        Location l = locMgr.getLastKnownLocation(bestProvider);
        getNewLocation(); 
    }catch(Exception e) {
        e.printStackTrace();
        System.out.println("error1");
    }


}


private boolean getNewLocation() {
    System.out.println("aaa");
    if(locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {                //This is executed since it can get locations faster than gps (is executed only if use wireless networks for locations is selected)  
        System.out.println("bbb");
            locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
            return true;                
    }else {                             
        return false;
    }      
}

public void onLocationChanged(Location lc) {
    System.out.println("ccc");
    if(lc!=null) {
            lat = lc.getLatitude();
            longt = lc.getLongitude();             
            System.out.println(lat + "xxx " + longt);
            //unregister the locationlistener once we get the locations
            locMgr.removeUpdates(this);
    }else {


    }

}
}
4

0 回答 0