如何一次使用地理编码和计时器

时间:2013-02-11 09:26:11

标签: android android-intent android-emulator

我创建了一个在地理编码器的帮助下管理地址的功能。 功能是:

 public String get_address(double latitude ,double longitude)
{
    String address=null;
    if(Geocoder.isPresent())
    {
        try{
            Geocoder geocoder2 = new Geocoder(mContext, Locale.getDefault());
              List<Address> addresses;
              addresses = geocoder2.getFromLocation(latitude, longitude, 2);
               if(addresses != null) {
                     Address returnedAddress = addresses.get(0);

                     StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                     //for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                    // strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    //}//or

                     if(returnedAddress.getMaxAddressLineIndex() > 0){
                         strReturnedAddress.append(returnedAddress.getAddressLine(0) + ", ");
                       }

                       strReturnedAddress.append(returnedAddress.getLocality() + ", ");
                       strReturnedAddress.append(returnedAddress.getCountryName());


                     address=strReturnedAddress.toString();
                     }
                     else{
                     address="No Address returned!";
                     }
               return address;

        }
        catch(Exception e)
        {
            Log.e("MyAPP", "Reverse geo lookup failed", e);
                address="reverse geo look up failed";
             return address;
        }

    }
    else
    {
        address="Geocoder is not present";
        return address;
    }

}

然后我每隔1分钟就会从定时器调用该函数编写代码我需要返回address.to开发这个定时器我使用run方法并进行调用

私有类mainTask扩展了TimerTask         {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            //String add=set_address();
             gps = new gpstracker(ctx);

                // check if GPS enabled
                if(gps.canGetLocation()){
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                   //String address=gps.convert_address();
                 String address2=gps.get_address(latitude, longitude);
                 address=address2;
                    // \n is for new line

                  //  Toast.makeText(getApplicationContext(), "address TWO ::"+address2, 500).show();
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                }

            toastHandler.sendEmptyMessage(0);
        }

    }

1 个答案:

答案 0 :(得分:0)

问题可能是您尝试访问

Address returnedAddress = addresses.get(1);

但它应该是

Address returnedAddress = addresses.get(0);

因为第一项有索引0。