警告对话框的主题 - 机器人 [英] Alert Dialog from Thread - Android

查看:81
本文介绍了警告对话框的主题 - 机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有发送GPS坐标,以每六秒钟数据库的螺纹和我有一个检查,验证该用户是一个定义的区域内。如果用户不在位置中,我想,通知他们,他们是超出范围的警告对话框,如果他们是在区域内我想一个对话框,告诉他们,他们都在范围之内。我有检查工作正常,但我已尽力,我pretty的肯定,我不能在后台线程中添加对话框。我读了一些关于使用处理程序,但我不知道如何实现的。如果您有任何建议,我会AP preciate吧!谢谢你。

这是我怎么叫 FindLocation.java 从我的主要活动( MainActivity.java ):

 新FindLocation(getBaseContext())启动(usr_id1)。 //将用户ID与它
 

下面是 FindLocation.java

 公共类FindLocation继承Thread {

公共布尔inJurisdiction;
公共布尔AlertNotice = FALSE;
私人LocationManager locManager;
私人LocationListener的locListener;

上下文CTX;
公共字符串userid;

公共FindLocation(上下文CTX){
     this.ctx = CTX;
}

 公共无效启动(字符串userid){
        this.userId =用户id;
        super.start();
      }

 @覆盖
公共无效的run(){
     活套prepare()。
    最后弦乐USR =用户id;

    //获取一个引用LocationManager
    locManager =(LocationManager)ctx.getSystemService(Context.LOCATION_SERVICE);

    //检查,以从位置接收更新
    locListener =新LocationListener的(){
        公共无效onLocationChanged(位置LOC){

            串纬度=将String.valueOf(loc.getLatitude());
            串经度=将String.valueOf(loc.getLongitude());

            双纬度= loc.getLatitude();
            双经度= loc.getLongitude();

            如果(北纬> = 39.15296&功放;&安培;经度> = -86.547546&功放;&安培;纬度和LT = 39.184901和放大器;&安培;经度<!= -86.504288 || inArea = FALSE){
                Log.i(测试,是);

                inArea = TRUE;

                JSONArray jArray;
                字符串结果= NULL;
                InputStream的是= NULL;
                StringBuilder的SB = NULL;

                 ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
                 nameValuePairs.add(新BasicNameValuePair(ID,USR));

                // HTTP POST
                尝试{

                     HttpClient的HttpClient的=新DefaultHttpClient();
                     HttpPost httppost =新HttpPost(http://www.example.com/test/example.php);
                     httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                     HTT presponse响应= httpclient.execute(httppost);
                     HttpEntity实体= response.getEntity();
                     是= entity.getContent();
                     }赶上(例外五){
                         Log.e(log_tag,错误的HTTP连接+ e.toString());
                    }

                //转换响应串
                尝试{
                      的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(就是,ISO-8859-1),8);
                       SB =新的StringBuilder();
                       sb.append(reader.readLine()+\ N);

                       串行=0;
                       而((行= reader.readLine())!= NULL){
                                      sb.append(行+\ N);
                        }
                        is.close();
                        结果= sb.toString();
                        }

                        赶上(例外五){
                              Log.e(log_tag,错误转换结果+ e.toString());


                        }

                尝试{
                      jArray =新JSONArray(结果);
                      JSONObject的json_data = NULL;
                      的for(int i = 0; I< jArray.length();我++){
                             json_data = jArray.getJSONObject(ⅰ);
                             串ct_name = json_data.getString(phoneID);
                             Log.i(用户ID,ct_name);
                             如果(ct_name == USR){
                                 locManager.removeUpdates(locListener);
                             }
                             其他{
                                 locManager.removeUpdates(locListener);
                                 Log.i(用户ID,无);
                             }
                         }
                      }

                      赶上(例外五){
                            //Log.e("log_tag,错误将导致+ e.toString());

                            HttpClient的HttpClient的=新DefaultHttpClient();
                            HttpPost httppost =新HttpPost(http://example.com/test/example.php);

                            尝试 {
                                   名单<的NameValuePair> nameValuePairs1 =新的ArrayList<的NameValuePair>(2);
                                   nameValuePairs1.add(新BasicNameValuePair(土地增值税,LAT));
                                   nameValuePairs1.add(新BasicNameValuePair(LON,LON));
                                   nameValuePairs1.add(新BasicNameValuePair(ID,USR));
                                   httppost.setEntity(新UrlEn codedFormEntity(nameValuePairs1));
                                   httpclient.execute(httppost);
                                   Log.i(SendLocation,是);
                             }
                             赶上(ClientProtocolException G){
                                 // TODO自动生成的catch块
                             }赶上(IOException异常F){
                                // TODO自动生成的catch块
                                e.printStackTrace();
                            }
                }
            }

            其他 {
                Log.i(测试,否);
                inArea = FALSE;
            }
        }
        公共无效onProviderDisabled(字符串提供商){
        }
        公共无效onProviderEnabled(字符串提供商){
        }
        公共无效onStatusChanged(字符串商,INT地位,捆绑演员){
        }
    };
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,6000,0,locListener);
    Looper.loop();
 }
}
 

解决方案

这是一个有点难以阅读整个code,但我会告诉你如何显示 AlertDialog 从后台

创建内部处理程序的onCreate() onResume() ...这上运行东西 UI线程

  ...的onCreate(){
... mHandler =新的处理程序();
}
 

那么你的发内()只需使用:

  mHandler.post(新的Runnable {
    公共无效的run(){
        //一定要通过你的活动类,而不是线程
        AlertDialog.Builder建设者=新AlertDialog.Builder(MyActivity.this);
        // ...设置对话框并显示
    }
});
 

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();
 }
}

解决方案

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
    }
});

这篇关于警告对话框的主题 - 机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆