2012-05-03 6 views
1

시나리오를 텍스트 뷰를 업데이트하지 않습니다지오 코더 AsyncTask를 백그라운드에서

그래서 내가 지금까지했던 (테스트 용) 매 3 분을 업데이트 지오 코더를 처리하기 위해 AsyncTask를 작성됩니다 것을. 그런 다음 4 분마다 사용자의 현재 주소로 토스트 메시지를 보여주는 TimerTask를 설정합니다. 내 응용 프로그램이 백그라운드에서 실행 중일 때

내 응용 프로그램에서 나는 모든 것이 괜찮 그러나, 토스트 메시지가 어떤 주소에 붙어 유지 : 그래서 heres는 문제를

을 (TimerTasks이 코드에 포함되지 않음) 앱이 내 앱을 종료하기 전에 마지막으로 설정되었습니다. AsyncTask가 백그라운드 (Checked LogCats)에서 실행되고 모든 것이 백그라운드에서 정상적으로 실행되고있는 것처럼 보입니다. 토스트에 현재 주소를 표시 할 수 없습니다.

모든 의견과 의견을 보내 주시면 감사하겠습니다. 여기

내 코드입니다 :

public class statuspage extends MapActivity { 

LocationManager locationManager; 
MapView mapView; 
Criteria criteria; 
Location location; 
Geocoder gc; 
Address address; 

String bestProvider; 
String LOCATION_SERVICE = "location"; 
String addressString = "Searching for Nearest Address"; 
StringBuilder sb; 

private MapController mapController; 
private MyLocationOverlay myLocation; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.statuspage); 

    // Get Mapping Controllers etc // 
    mapView = (MapView) findViewById(R.id.mapView); 
    mapController = mapView.getController(); 
    mapController.setZoom(17); 
    mapView.setBuiltInZoomControls(true); 

    // Add the MyLocationOverlay // 
    myLocation = new MyLocationOverlay(this, mapView); 
    mapView.getOverlays().add(myLocation); 
    myLocation.enableCompass(); 
    myLocation.enableMyLocation(); 

    // Animates the map to GPS Position // 
    myLocation.runOnFirstFix(new Runnable() { 
     @Override 
     public void run() { 
      mapController.animateTo(myLocation.getMyLocation()); 

     } 
    }); 
} 

@Override 
protected boolean isRouteDisplayed() { 

    // Location Manager Intiation 
    locationManager = (LocationManager) statuspage.this 
      .getSystemService(LOCATION_SERVICE); 
    criteria = new Criteria(); 

    // More accurate, GPS fix. 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix. 
    bestProvider = locationManager.getBestProvider(criteria, true); 

    location = locationManager.getLastKnownLocation(bestProvider); 
    updateWithNewLocation(location); 

    locationManager.requestLocationUpdates(bestProvider, 60000, 10, 
      locationListener); // 1800000 = 30 Min 

    return false; 
} 

class GeoCoder extends AsyncTask<Void, Void, Void> { 

    String lat = "Acquiring"; 
    String lng = "Acquiring"; 

    @Override 
    protected Void doInBackground(Void... params) { 
     if (location != null) { 

      /** 
      * double latitude = myLocation.getMyLocation().getLatitudeE6(); 
      * double longitude = 
      * myLocation.getMyLocation().getLongitudeE6(); 
      */ 

      double latitude = location.getLatitude(); 
      double longitude = location.getLongitude(); 

      lat = "" + latitude; 
      lng = "" + longitude; 

      // gc = new Geocoder(statuspage.this, Locale.getDefault()); 
      Geocoder gc = new Geocoder(getApplicationContext(), 
        Locale.getDefault()); 
      try { 

       List<Address> addresses = gc.getFromLocation(latitude, 
         longitude, 1); 

       sb = new StringBuilder(); 
       if (addresses != null && addresses.size() > 0) { 
        address = addresses.get(0); 

        int noOfMaxAddressLine = address 
          .getMaxAddressLineIndex(); 
        if (noOfMaxAddressLine > 0) { 
         for (int i = 0; i < address 
           .getMaxAddressLineIndex(); i++) { 
          sb.append(address.getAddressLine(i)).append(
            "\n"); 
         } 
         addressString = sb.toString(); 

        } 
       } 
      } catch (Exception e) { 

       addressString = "Sorry, we are trying to find information about this location"; 
      } 

     } 
     return null; 
    } 


    @Override 
    protected void onPostExecute(Void result) { 
     TextView scrollview = (TextView) findViewById(R.id.scrollview); 

     // Latitude and Longitude TextView 
     TextView etlongitude = (TextView) findViewById(R.id.etlongitude); 
     TextView etlatitude = (TextView) findViewById(R.id.etlatitude); 

     // TextView to display GeoCoder Address 
     scrollview.setGravity(Gravity.CENTER); 
     scrollview.setText("Your location:" + "\n" 
       + "(Accurate to 500 meters)" + "\n" + (addressString)); 

     Log.d("Address", (addressString)); 

     // Latitude and Longitude TextView Display Coordinates // 
     etlongitude.setText(lng); 
     etlatitude.setText(lat); 

     // Log.d("GeoCoder", "In-Task"); 

     return; 
    } 
+0

누구든지 도움을받을 수 있습니까? –

답변

0

당신이를 연결하는 유일한 방법 background.The에서 내부 스레드 그게 전부에서 UI를 연결할 수 불가능 background.Its의 UI를 업데이트하지 못할 assync 작업을 사용하는 UI는 onPostExecute()를 사용하고이 onPostExecute() 함수를 사용하여 배경에서 메시지를 보내는 UI.try를 업데이트하고 메시지를 확인하여 postexecute에서 UI 작업을 수행합니다. 그러면 도움이 될 것입니다.

+0

고마운 스리, 아픈 이것에 대한 연구를하려고합니다. 자세한 내용을 설명 할 수있는 링크를 제공해 주시겠습니까? –

0

동일한 문제가 있습니다. 현재 활동에 머물러도 문제가 없지만 doInBackgroud이 실행되는 동안 활동을 종료하면 onPostExecute은 토스트 라인에서 종료됩니다.

이 문제를 해결하려면, 당신은 핸들러를 사용해야합니다 : 코드에서 onPostExecute()

Message msg = new Message(); 
msg.what = TOAST; 
msg.obj = "my toast message"; 
mHandler.sendMessage(msg); 

에서 OnCreate()

// Creation of the handler to display Toasts 
if (mHandler == null) { 
    mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message _msg) { 
      switch (_msg.what) { 
      case TOAST: 
      Toast.makeText(ServerTabHost.this, (String)_msg.obj, Toast.LENGTH_LONG).show(); 
      break; 
      default : break; 
     } 
     super.handleMessage(_msg); 
     } 
    }; 
} 

에서
클래스

private static final int TOAST = 0; 
private Handler mHandler = null; 

에서 그것을 그대의 모습이다. S : 내가 호스트 활동의 핸들러를 만든 다음 조각 생성자에 전달했다, 그래서 개인적으로

public class statuspage extends MapActivity { 

// These two lines are for the handler 
private static final int TOAST = 0; 
private Handler mHandler = null; 

LocationManager locationManager; 
MapView mapView; 
Criteria criteria; 
Location location; 
Geocoder gc; 
Address address; 

String bestProvider; 
String LOCATION_SERVICE = "location"; 
String addressString = "Searching for Nearest Address"; 
StringBuilder sb; 

private MapController mapController; 
private MyLocationOverlay myLocation; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.statuspage); 

    // Get Mapping Controllers etc // 
    mapView = (MapView) findViewById(R.id.mapView); 
    mapController = mapView.getController(); 
    mapController.setZoom(17); 
    mapView.setBuiltInZoomControls(true); 

    // Add the MyLocationOverlay // 
    myLocation = new MyLocationOverlay(this, mapView); 
    mapView.getOverlays().add(myLocation); 
    myLocation.enableCompass(); 
    myLocation.enableMyLocation(); 

    // Animates the map to GPS Position // 
    myLocation.runOnFirstFix(new Runnable() { 
     @Override 
     public void run() { 
      mapController.animateTo(myLocation.getMyLocation()); 

     } 
    }); 

    // Creation of the handler to display Toasts 
    if (mHandler == null) { 
     mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message _msg) { 
      switch (_msg.what) { 
       case TOAST: 
       Toast.makeText(ServerTabHost.this, (String)_msg.obj, Toast.LENGTH_LONG).show(); 
       break; 
       default : break; 
      } 
      super.handleMessage(_msg); 
      } 
     }; 
    } 
} 

@Override 
protected boolean isRouteDisplayed() { 

    // Location Manager Intiation 
    locationManager = (LocationManager) statuspage.this 
      .getSystemService(LOCATION_SERVICE); 
    criteria = new Criteria(); 

    // More accurate, GPS fix. 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix. 
    bestProvider = locationManager.getBestProvider(criteria, true); 

    location = locationManager.getLastKnownLocation(bestProvider); 
    updateWithNewLocation(location); 

    locationManager.requestLocationUpdates(bestProvider, 60000, 10, 
      locationListener); // 1800000 = 30 Min 

    return false; 
} 

class GeoCoder extends AsyncTask<Void, Void, Void> { 

    String lat = "Acquiring"; 
    String lng = "Acquiring"; 

    @Override 
    protected Void doInBackground(Void... params) { 
     if (location != null) { 

      /** 
      * double latitude = myLocation.getMyLocation().getLatitudeE6(); 
      * double longitude = 
      * myLocation.getMyLocation().getLongitudeE6(); 
      */ 

      double latitude = location.getLatitude(); 
      double longitude = location.getLongitude(); 

      lat = "" + latitude; 
      lng = "" + longitude; 

      // gc = new Geocoder(statuspage.this, Locale.getDefault()); 
      Geocoder gc = new Geocoder(getApplicationContext(), 
        Locale.getDefault()); 
      try { 

       List<Address> addresses = gc.getFromLocation(latitude, 
         longitude, 1); 

       sb = new StringBuilder(); 
       if (addresses != null && addresses.size() > 0) { 
        address = addresses.get(0); 

        int noOfMaxAddressLine = address 
          .getMaxAddressLineIndex(); 
        if (noOfMaxAddressLine > 0) { 
         for (int i = 0; i < address 
           .getMaxAddressLineIndex(); i++) { 
          sb.append(address.getAddressLine(i)).append(
            "\n"); 
         } 
         addressString = sb.toString(); 

        } 
       } 
      } catch (Exception e) { 

       addressString = "Sorry, we are trying to find information about this location"; 
      } 

     } 
     return null; 
    } 


    @Override 
    protected void onPostExecute(Void result) { 

     // Sending the Toast message through the handler 
     Message msg = new Message(); 
    msg.what = TOAST; 
    msg.obj = "My toast message"; 
    mHandler.sendMessage(msg); 

     TextView scrollview = (TextView) findViewById(R.id.scrollview); 

     // Latitude and Longitude TextView 
     TextView etlongitude = (TextView) findViewById(R.id.etlongitude); 
     TextView etlatitude = (TextView) findViewById(R.id.etlatitude); 

     // TextView to display GeoCoder Address 
     scrollview.setGravity(Gravity.CENTER); 
     scrollview.setText("Your location:" + "\n" 
       + "(Accurate to 500 meters)" + "\n" + (addressString)); 

     Log.d("Address", (addressString)); 

     // Latitude and Longitude TextView Display Coordinates // 
     etlongitude.setText(lng); 
     etlatitude.setText(lat); 

     // Log.d("GeoCoder", "In-Task"); 

     return; 
    } 

, 내가 조각했다.

+0

전 핸들러를 다루지 않았습니다. 도움과 안내에 감사드립니다. 더 잘 이해하기 위해 핸들러를 연구 중입니다. 지금까지, 당신이 제안한 것은 내 취향에 맞춰 작동하는 것 같습니다. 감사합니다 Elasticboy! –

+0

죄송합니다. 제 질문이 약간 잘못된 것입니다. 토스트 메시지가 잘 나타나는데, 내 앱 (예를 들어 웹 탐색)에 있지 않을 때 내 토스트 메시지가 현재 활동에있을 때 제공 한 주소에 머물러있게됩니다. 내 앱으로 돌아갈 때까지 같은 주소. 내 활동으로 돌아올 때까지 주소가 업데이트되지 않습니다. –

+0

토스트 메시지가 표시되지만 사용되지 않는 정보가 표시됩니까? –

관련 문제