1

I have a thread that sends GPS coordinates to a database every six seconds and I have a check that verifies that the user is within a defined area. If the user is not within the location, I want an alert dialog that notifies them that they are out of range, and if they are within the area I want a dialog that tells them they are within range. I have the checks working properly, but I have tried and I'm pretty sure that I can't add the dialog on the background thread. I have read a bit about using handlers but I'm not sure how to implement one. If you have any suggestions I would appreciate it! Thanks.

This is how I call FindLocation.java from my main activity (MainActivity.java):

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

Below is 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();
 }
}
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
mkyong
  • 12,497
  • 12
  • 37
  • 56

3 Answers3

10

It is a little difficult to read the entire code, but I will show you how to display an AlertDialog from a background Thread:

Create a handler inside onCreate(), or onResume()... something that runs on the UI-Thread:

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

Then inside your Thread() just use:

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
    }
});
LBes
  • 3,366
  • 1
  • 32
  • 66
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
  • I understand this, but I call this from my main activity and the entire class is essentially a thread. Since I don't have an onCreate for the the class, where would I instantiate the handler object? – mkyong Apr 03 '12 at 09:52
  • you could just pass it as a parameter in the constructor of your Thread. the same way you pass the context. – Ovidiu Latcu Apr 03 '12 at 09:54
9
     runOnUiThread(new Runnable() {
                     public void run() {

                              //your alert dialog here..

                    }
                });
5hssba
  • 8,079
  • 2
  • 33
  • 35
  • Where would I put this in the FindLocation class? Also, how do I call it? Would I use this twice, once if the user is within the defined location and once again if they are not? Thanks – mkyong Apr 03 '12 at 10:38
  • see... whenever you want to display the alertdialog.. put this entire part there.. and create the alert dialog inside.. – 5hssba Apr 03 '12 at 10:38
  • Ok I see. I have done that, but I get an error `The method runOnUiThread(new Runnable(){}) is undefined for the type new LocationListener(){}` when I put it directly under `inArea = true;` (after the if(latitude >= ...)) Any idea why? – mkyong Apr 03 '12 at 10:43
  • Same problem, but says "... is undefined for the type FindLocation." Got any other ideas? – mkyong Apr 03 '12 at 10:55
  • [See this to use handler..](http://stackoverflow.com/questions/4369537/update-ui-from-thread) – 5hssba Apr 03 '12 at 11:04
  • Well I'd like to continue using the thread. I had a lot of trouble getting the AsyncTask to work. Do I need to define something first? – mkyong Apr 03 '12 at 11:12
  • I couldn.t get you.. did you see his answer?[Arhimed](http://stackoverflow.com/questions/4369537/update-ui-from-thread) – 5hssba Apr 03 '12 at 11:14
  • See... i said youractivity.this.runonui thread.. and u were using a thread inplace of activity... put MainActivity.this.runonUithread... – 5hssba Apr 03 '12 at 11:17
  • Did you try putting your activity name? – 5hssba Apr 03 '12 at 11:25
2
new Handler().post(new Runnable{
 public void run(){

   //create your AlertDialog here.. 
  }

});

see more here

ngesh
  • 13,398
  • 4
  • 44
  • 60