java - 来自 Thread 的警报对话框 - Android

标签 java android multithreading handler android-alertdialog

我有一个线程每六秒将 GPS 坐标发送到数据库,并且我有一个检查来验证用户是否在定义的区域内。如果用户不在该位置内,我想​​要一个警告对话框,通知他们他们超出了范围,如果他们在该区域内,我想要一个对话框告诉他们他们在范围内。我的检查工作正常,但我已经尝试过并且我很确定我无法在后台线程上添加对话框。我已经阅读了一些有关使用处理程序的内容,但我不确定如何实现。如果您有任何建议,我将不胜感激!谢谢。

这就是我从主要 Activity (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();
 }
}

最佳答案

阅读整个代码有点困难,但我将向您展示如何从后台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
    }
});

关于java - 来自 Thread 的警报对话框 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990242/

相关文章:

c++ - 为什么要使用 std::mutex 而不是 boost::shared_mutex?

java - 使用 Java 批量上传到 Box*

java - 超越 Java 中的 Integer.MAX_VALUE 约束

java - 有什么方法可以为独立应用程序加密 persistence.xml 吗?

c# - 无法通过 Wifi 从 Android 应用程序访问另一台机器中存在的图像文件夹

android: use-feature 中的 "required"和 user-permission 中的 "requiredFeature"有什么区别?

c# - 使 [IsOneWay=true] WCF 服务异步与在客户端使用任务调用同步方法之间是否存在显着差异?

java - 无法使用Retrofit在ListView中显示数据

java - 如何在未经用户同意的情况下在 ICS 上安装 (x509/pk12) 证书?

java - 如何显示具有不同属性的多个数据列表