2013-07-07 75 views
0

我想要做的是在用戶點擊一個名爲location_Button的按鈕後獲取用戶的位置,然後顯示一個顯示有關其位置信息的框。我嘗試過這樣的:進度對話框不排除

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:

​​
+0

確定,但我很不確定究竟在哪裏放置'最終的LocationManager locationManager =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE); geocoder = new Geocoder(this,Locale.getDefault());' – ez4nick

+0

你可以把代碼放在doinbackground函數中。 –