java - 线程和上下文之间的问题 - Android

标签 java android multithreading android-context

我正在尝试实现一个线程,以便我可以在后台发送 GPS 坐标。我认为我有一个良好的开端,但我遇到了一些麻烦。哪里写着locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);我在上下文中收到错误(在 getSystemService 之前),提示“上下文无法解析”。我使用以下语句从我的主要 Activity 中调用此类 new FindLocation(getBaseContext()).start(usr_id1);也许这与问题有关。如果您有任何建议,请让我知道!

public class FindLocation extends Thread {

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() {
    final String usr = userId;

    //get a reference to the LocationManager
    locManager = (LocationManager) context.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());

            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");
                         //stop = true;
                         Log.i("User ID", ct_name);
                         if(ct_name == usr) {
                             locManager.removeUpdates(locListener);
                         }
                         else{
                             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();
                        } 
            } 
        }       


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

}

最佳答案

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

根据您发布的内容,您应该使用 ctx 而不是 context

关于java - 线程和上下文之间的问题 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9972347/

相关文章:

java - 表单验证后的消息

使用数据路径的 Android Intent 过滤器

android - 我应该为这个 android UI 使用什么控件?

java - 从连接到 Android 的传感器(线程、异步任务、服务)连续获取数据

java - Maven、Vaadin 和资源文件夹

java - Eclipse:创建包含一个类+依赖项的 jar

android - 如何在 ImageViews (parse.com) 中加载多个图像

c - 多处理器系统上的线程

c++ - 主机和目标的 Makefile

java - 如何在 NetBeans 上放大/缩小 View 设计