私はジオコーダーの助けを借りて住所を大切にする1つの関数を作成しました。関数は:
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分ごとにタイマーからその関数の呼び出しにコードを記述します。アドレスを返す必要があります。このタイマーを開発するには、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);
}
}