2013-07-07 2 views
0

То, что я пытаюсь сделать, это получить местоположение пользователя после нажатия кнопки, называемой location_Button, а затем отобразить окно, в котором отображается информация об их местоположении. Я пробовал вот так:progress dialog не увольняет

Button location_Button=(Button) findViewById(R.id.location_button); 
    location_Button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // Define a listener that responds to location updates 
      progressDialog = ProgressDialog.show(Settings.this, "", "Loading..."); 

      final LocationListener locationListener = new LocationListener() { 

       public void onLocationChanged(Location location) { 
        // Called when a new location is found by the network location provider. 

        lat =location.getLatitude(); 
        lon = location.getLongitude(); 
        try{ 

         addresses=(geocoder.getFromLocation(lat, lon, 1)); 
         if (addresses.size() > 0) { 
          String city = addresses.get(0).getAddressLine(1); 
          String id = city.substring(0,city.length()-5); 
          String state1=String.valueOf(id.charAt(id.length()-3)); 
          String state2=String.valueOf(id.charAt(id.length()-2)); 
          String STATE = state1+state2; 

          locationManager.removeUpdates(this); 
          progressDialog.dismiss(); 

          //alert dialog is established and displayed here 



         } 
         else { 
          //tv.setText("Oops..."); 
         } 

        }catch(IOException e){ 
         e.printStackTrace(); 
        } 

       } 

       public void onStatusChanged(String provider, int status, Bundle extras) {} 

       public void onProviderEnabled(String provider) {} 

       public void onProviderDisabled(String provider) {} 
      }; 

И проблема в том, что диалог прогресса никогда не отклоняется. без диалога прогресса, когда кнопка нажата, он ищет, а затем показывает окно, в диалоговом окне прогресса он продолжает говорить о загрузке и никогда не упускается. моя цель состоит в том, чтобы диалог прогресса был отклонен после того, как местоположение установлено, также появится диалоговое окно предупреждения, но это не так. Неправильное расположение диалога прогресса?

ответ

1

Просто потому, что Android всегда асинхронен, вы должны использовать поток для использования диалогов прогресса. Пример:

В вашем коде, если вы хотите, чтобы начать диалог, вызовите асинхронный класс:

Button location_Button=(Button) findViewById(R.id.location_button); 
    location_Button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      LocationChanged locationChanged = new LocationChanged(MainActivity.this, "Loading..."); 
      locationChanged.execute(); 
     } 

Теперь вам нужно создать LocationChanged.java:

import android.app.ProgressDialog; 
import android.content.Context; 
import android.os.AsyncTask; 

public class LocationChanged extends AsyncTask<Void, Void, Void> { 

    private ProgressDialog progressDialog; 
    private Context context; 
     private String message; 

    public LocationChanged (Context context, String message) { 
     this.context = context; 
       this.message = message; 
     } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     progressDialog = ProgressDialog.show (context, null, message); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
      // Here you add your code. 

      return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute (result); 

     progressDialog.dismiss(); 

      // You can add code to be executed after the progress (may be a result). 
    } 

} 
+0

нормально, но я не уверен, где именно поставить «конечный LocationManager locationManager = (LocationManager) this.getSystemService (Context.LOCATION_SERVICE); geocoder = новый геокодер (это, Locale.getDefault()); – ez4nick

+0

Вы можете поместить код внутри функции doinbackground. –

Смежные вопросы