簡體   English   中英

來自線程的警報對話框-Android

[英]Alert Dialog from Thread - Android

我有一個線程,每隔六秒鍾將GPS坐標發送到數據庫,並且有一個檢查可以驗證用戶是否在定義的區域內。 如果用戶不在該位置內,則我需要一個警報對話框,通知他們它們不在范圍內;如果用戶在該區域內,我想要一個對話框,告訴他們它們在范圍內。 我的檢查工作正常,但是我已經嘗試過了,而且我很確定我不能在后台線程上添加對話框。 我已經讀過一些有關使用處理程序的信息,但是我不確定如何實現。 如果您有任何建議,我將不勝感激! 謝謝。

這是我從主要活動( MainActivity.java )中調用FindLocation.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();
 }
}
     runOnUiThread(new Runnable() {
                     public void run() {

                              //your alert dialog here..

                    }
                });

閱讀整個代碼有點困難,但是我將向您展示如何從后台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
    }
});
new Handler().post(new Runnable{
 public void run(){

   //create your AlertDialog here.. 
  }

});

在這里看到更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM