Android:异步任务|在后台冻结UI?

时间:2016-05-10 07:58:44

标签: android multithreading android-asynctask

我遇到了问题,并且已经查看了所有地方(youtube,dev网站)的解决方案,但我找不到。

我的应用程序中的UI在凌空连接启动时挂起,我将它添加到AsyncTask重写DoInBackground方法但它仍然挂起。

我通过齐射处理连接的代码是:

public class DoInBackground extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... arg0) {
        //Adding cameras from server using volley...
        String url = "FullUrlHere";
        JSONArray jArray = new JSONArray();

        JsonArrayRequest jArrayReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                //Response received
                try {
                    int sizeOfArray = response.getInt(0);
                    String element = response.getString(1);

                    //Toast.makeText(getApplicationContext(), "Size: " + sizeOfArray, Toast.LENGTH_LONG).show();
                    //Now we have the size of array, now to cycle through them
                    for (int i = 1; i < sizeOfArray + 1; i++) {
                        //Cycle through
                        String nextAddress = response.getString(i);
                        //Put into our array
                        cameraAddresses.add(nextAddress);
                    }

                    for (String address : cameraAddresses) {
                        String camAddress = address;
                        //Toast.makeText(getApplicationContext(), latitudeValue, Toast.LENGTH_LONG).show();

                        //Start reverse geo coding. (Turning address into coordinates.)
                        Geocoder camLocationGeocoder = new Geocoder(getApplicationContext());
                        List<Address> addresses;
                        addresses = camLocationGeocoder.getFromLocationName(address, 1);
                        if (addresses.size() > 0) {
                            double latitude = addresses.get(0).getLatitude();
                            double longitude = addresses.get(0).getLongitude();
                            //Add markers.
                            Marker camera = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Possible Speed Camera.").icon(BitmapDescriptorFactory.fromResource(R.drawable.camera_placemarker)));
                            cameraList.add(camera);
                        }

                    }
                } catch (Exception e) {
                    //Error caught.
                    //Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Error
                //Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
            }
        });

        MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jArrayReq);
        return null;
    }
}


private void addLocations() {
    //Below code to be performed on BG thread

    for (Marker camera : cameraList) {
        camera.remove(); //Remove camera, we will re-add them in a while.
    }
    cameraList.clear(); //Remove all cameras from arrayList

    //Execute Task
    new DoInBackground().execute();
}

2 个答案:

答案 0 :(得分:0)

  

在后台冻结UI吗?

doInBackground,因为名称表示正在运行seapare,没有UI线程。它不会阻止UI线程(但它可能会导致重负载,也会影响UI线程,但其他故事)。

答案 1 :(得分:0)

您是否尝试覆盖onPostExecuteonProgressUpdate

AsyncTask有4种方法:

  • onPreExecute() - &gt;在调用doInBacground()之前在主线程中运行
  • doInBackground(Object[] params) - &gt;在后台运行,无法与UI交互
  • onProgressUpdate(Object[] values) - &gt;在publishProgress(Object... values)
  • 中调用方法doInBackground时,在主线程中运行
  • onPostExecute(Object result) - &gt; doInBackground结束任务时在主线程中运行

我不确定您用于创建摄像机的方法是否必须在主线程中执行,但如果您尚未解决问题,则可以尝试将新摄像机实例化为{{1}每次有数据创建摄像头时,从onProgressUpdate调用publishProgress

我希望它可以帮到你。