2012-04-03 30 views
1

我有一個線程每六秒向站點發送一次GPS座標,我有一個檢查來驗證用戶是否在一個已定義的區域內。如果用戶不在該位置,我想要一個警告對話框,通知他們他們超出範圍,如果他們在該區域內,我想要一個對話框來告訴他們他們在範圍內。我有檢查工作正常,但我已經嘗試過,我敢肯定,我不能在後臺線程添加對話框。我已閱讀了一些關於使用處理程序的內容,但我不確定如何實現它。如果您有任何建議,我將不勝感激!謝謝。來自線程的警報對話框 - Android

這是我怎麼稱呼FindLocation.java從我的主要活動(MainActivity.java):

new FindLocation(getBaseContext()).start(usr_id1); //sends a user id with it 

下面是FindLocation.java

public class FindLocation extends Thread { 

public boolean inJurisdiction; 
public boolean AlertNotice = false; 
private LocationManager locManager; 
private LocationListener locListener; 

Context ctx; 
public String userId; 

public FindLocation(Context ctx) { 
    this.ctx = ctx; 
} 

public void start(String userId) { 
     this.userId = userId; 
     super.start(); 
     } 

@Override 
public void run() { 
    Looper.prepare(); 
    final String usr = userId;  

    //get a reference to the LocationManager 
    locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE); 

    //checked to receive updates from the position 
    locListener = new LocationListener() { 
     public void onLocationChanged(Location loc) { 

      String lat = String.valueOf(loc.getLatitude()); 
      String lon = String.valueOf(loc.getLongitude()); 

      Double latitude = loc.getLatitude(); 
      Double longitude = loc.getLongitude(); 

      if (latitude >= 39.15296 && longitude >= -86.547546 && latitude <= 39.184901 && longitude <= -86.504288 || inArea != false) { 
       Log.i("Test", "Yes"); 

       inArea = true; 

       JSONArray jArray; 
       String result = null; 
       InputStream is = null; 
       StringBuilder sb = null; 

       ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("id", usr)); 

       //http post 
       try{ 

        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");  
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 
        }catch(Exception e){ 
         Log.e("log_tag", "Error in http connection"+e.toString()); 
        } 

       //convert response to string 
       try{ 
         BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
         sb = new StringBuilder(); 
         sb.append(reader.readLine() + "\n"); 

         String line="0"; 
         while ((line = reader.readLine()) != null) { 
             sb.append(line + "\n"); 
         } 
         is.close(); 
         result=sb.toString(); 
         } 

         catch(Exception e){ 
           Log.e("log_tag", "Error converting result "+e.toString()); 


         } 

       try{ 
         jArray = new JSONArray(result); 
         JSONObject json_data=null; 
         for(int i=0;i<jArray.length();i++){ 
          json_data = jArray.getJSONObject(i); 
          String ct_name = json_data.getString("phoneID"); 
          Log.i("User ID", ct_name); 
          if(ct_name == usr) { 
           locManager.removeUpdates(locListener); 
          } 
          else{ 
           locManager.removeUpdates(locListener); 
           Log.i("User ID", "NONE"); 
          } 
         } 
         } 

         catch(Exception e){ 
          //Log.e("log_tag", "Error converting result "+e.toString()); 

          HttpClient httpclient = new DefaultHttpClient(); 
          HttpPost httppost = new HttpPost("http://example.com/test/example.php"); 

          try { 
            List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2); 
            nameValuePairs1.add(new BasicNameValuePair("lat", lat)); 
            nameValuePairs1.add(new BasicNameValuePair("lon", lon)); 
            nameValuePairs1.add(new BasicNameValuePair("id", usr)); 
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1)); 
            httpclient.execute(httppost); 
            Log.i("SendLocation", "Yes"); 
          } 
          catch (ClientProtocolException g) { 
           // TODO Auto-generated catch block 
          } catch (IOException f) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
       } 
      } 

      else { 
       Log.i("Test", "No"); 
       inArea = false; 
      } 
     } 
     public void onProviderDisabled(String provider){ 
     } 
     public void onProviderEnabled(String provider){ 
     } 
     public void onStatusChanged(String provider, int status, Bundle extras){ 
     } 
    }; 
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener); 
    Looper.loop(); 
} 
} 

回答

9

這是一個有點難以閱讀整個代碼,但我會告訴你如何從背景Thread顯示AlertDialog

創建內部onCreate(),或onResume()處理程序...的東西,在UI-Thread運行:

...onCreate(){ 
     //... 
     mHandler=new Handler(); 
} 

內。然後你Thread()只需使用:

mHandler.post(new Runnable() { 
    public void run(){ 
     //Be sure to pass your Activity class, not the Thread 
     AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this); 
     //... setup dialog and show 
    } 
}); 
+0

我明白這一點,但我從我的主要活動中調用這個,整個班級本質上是一個線程。由於我沒有這個類的onCreate,我會在哪裏實例化處理程序對象? – mkyong 2012-04-03 09:52:45

+0

您可以將它作爲線程的構造函數中的參數傳遞。與傳遞上下文的方式相同。 – 2012-04-03 09:54:36

2
new Handler().post(new Runnable{ 
public void run(){ 

    //create your AlertDialog here.. 
    } 

}); 

看到更多here

8
 runOnUiThread(new Runnable() { 
        public void run() { 

           //your alert dialog here.. 

        } 
       }); 
+0

我會在哪裏把這個在FindLocation類?另外,我怎樣稱呼它?我會使用這兩次,一次如果用戶在定義的位置,並再次,如果他們不是?謝謝 – mkyong 2012-04-03 10:38:01

+0

看到...只要你想顯示alertdialog ..把整個部分在那裏..並創建內部的警報對話框.. – 5hssba 2012-04-03 10:38:57

+0

好吧,我明白了。我已經這樣做了,但是我得到了一個錯誤:當我把它放在'inArea = true;'(在if後面時,方法runOnUiThread(new Runnable(){})未定義爲newLocationListener(){} (緯度> = ...))任何想法爲什麼? – mkyong 2012-04-03 10:43:54