android-fragments 在嵌套片段中运行多个AsyncTasks时挂起线程,这会使应用变慢

dl5txlt9  于 2022-11-14  发布在  Android
关注(0)|答案(3)|浏览(119)

这里我调用嵌套片段中的Web服务,其中包含TabLayout和使用AsyncTaskViewPager。我已经尝试过在每个FragmentonResume方法中调用AsyncTasks

new FetchAllData(getActivity()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

new FetchAllData(getActivity()).execute();

一切都很好,但我有很多问题:

  • 应用程序停止工作,没有任何对话框,但在logcat中显示suspending all threads
  • 当我们从图像中显示的另一个Activity访问这个片段(它有嵌套的tablayouts和viewpagers)时,除了工具栏之外,所有内容都空白了3到5秒。突然之间,它们就有了完整的数据。
  • 当我们从另一个相同活动的片段调用这个片段时,它在那里冻结,而这个片段在那里突然打开。

我希望你得到了我的所有问题,如果没有请通知我。
堆栈跟踪为:

1-29 12:10:49.580 10853-10863/com.cws.advisorymandi W/art: Suspending all threads took: 10.409ms
 01-29 12:10:49.707 10853-10853/com.cws.advisorymandi D/cr_Ime: [InputMethodManagerWrapper.java:27] Constructor
 01-29 12:10:49.711 10853-10853/com.cws.advisorymandi D/cr_Ime: [ImeAdapter.java:241] attach
 01-29 12:10:49.711 10853-10853/com.cws.advisorymandi W/art: Attempt to remove local handle scope entry from IRT, ignoring
 01-29 12:10:49.716 10853-10853/com.cws.advisorymandi W/AwContents: onDetachedFromWindow called when already detached. Ignoring
 01-29 12:10:49.717 10853-10853/com.cws.advisorymandi D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: false
 01-29 12:10:49.726 10853-10853/com.cws.advisorymandi W/art: Attempt to remove local handle scope entry from IRT, ignoring
 01-29 12:10:49.726 10853-10853/com.cws.advisorymandi W/art: Attempt to remove local handle scope entry from IRT, ignoring
 01-29 12:10:49.812 10853-10853/com.cws.advisorymandi D/cr_Ime: [ImeAdapter.java:241] attach
 01-29 12:10:49.832 10853-10853/com.cws.advisorymandi D/cr_Ime: [ImeAdapter.java:241] attach
 01-29 12:10:49.833 10853-10853/com.cws.advisorymandi I/Choreographer: Skipped 58 frames!  The application may be doing too much work on its main thread.
 01-29 12:10:50.075 10853-10853/com.cws.advisorymandi W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 10853
 01-29 12:10:50.610 10853-10863/com.cws.advisorymandi W/art: Suspending all threads took: 43.636ms
 01-29 12:10:50.621 10853-10853/com.cws.advisorymandi I/Ads: Scheduling ad refresh 60000 milliseconds from now.
 01-29 12:10:50.630 10853-10853/com.cws.advisorymandi I/Ads: Ad finished loading.

Fragment.java

public class IndicesFragment extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
public static String imagepath = null;
public static FetchAllData myTask;
static ArrayList<EquityDetails> catListDao = new ArrayList<EquityDetails>();
static ArrayList<EquityDetails> catListDao1 = new ArrayList<EquityDetails>();
static int count = 0;
static int count1 = 0;
ListView list;
ImageView progressBar;
View view;
Activity act;
AdvisorsAdapter adapter;
TextView empty_text;
AnimatorSet set;
JSONArray jsonArray;
SwipeRefreshLayout swipeRefreshLayout;
private boolean isViewShown = false;

public static IndicesFragment newInstance() {
    return new IndicesFragment();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        isViewShown = true;
        if (adapter != null) {
            adapter.filter("");
        }
    } else {
        isViewShown = false;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.equity_activity, container, false);
    act = this.getActivity();
    Constants.check_fragment_visible = 1;
    count++;
    setHasOptionsMenu(true);
    list = (ListView) view.findViewById(R.id.list_equity);
    empty_text = (TextView) view.findViewById(R.id.empty);
    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
    progressBar = (ImageView) view.findViewById(R.id.progressBar);
    set = (AnimatorSet) AnimatorInflater.loadAnimator(getActivity(), R.animator.fadein);
    set.setTarget(progressBar);
    progressBar.setVisibility(View.GONE);
    if (Utils.isNetworkAvailable(getActivity())) {
        if (catListDao.size() > 0) {
            adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 0);
            list.setAdapter(adapter);
        } else {
            if (!isViewShown) {
                new FetchAllData(getActivity(), 3).execute();
            }
        }
    } else {
        CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
    }
    swipeRefreshLayout.setOnRefreshListener(this);
    return view;
}

public void onActivityCreated(Bundle savedInstanceState1) {
    super.onActivityCreated(savedInstanceState1);
}

@Override
public void onResume() {
    super.onResume();
    Constants.check_fragment_visible = 1;
    if (Constants.check_reload) {
        if (Utils.isNetworkAvailable(getActivity())) {
            new FetchAllData(getActivity(), 3).execute();
        } else {
            CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
        }
    }
    if (adapter != null) adapter.notifyDataSetChanged();

}

@Override
public void onRefresh() {
    if (Utils.isNetworkAvailable(getActivity())) {
        new FetchAllData(getActivity(), 3).execute();
    } else {
        CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
    }
}

public void doChange(String queryText) {
    if (queryText != null) {
        if (adapter != null)
            adapter.filter(queryText);
    }
}

public void parseJSON(String result) {
    if (result != null) {
        JSONObject jsonObject;
        try {
            catListDao = new ArrayList<EquityDetails>();
            jsonObject = new JSONObject(result);
            jsonArray = jsonObject.getJSONArray("list");

            Log.d("Length ", "" + jsonArray.length());
            for (int i = 0; i < jsonArray.length(); i++) {
                EquityDetails allDirectory = new EquityDetails();
                allDirectory.setEntry_value(jsonArray.getJSONObject(i).getString("entry"));
                String value1 = jsonArray.getJSONObject(i).getString("entry");
                String value2 = jsonArray.getJSONObject(i).getString("tgt_1");
                allDirectory.setSerial_value(jsonArray.getJSONObject(i).getString("sl"));
                allDirectory.setTg_value1(jsonArray.getJSONObject(i).getString("tgt_1"));
                allDirectory.setTg_value2(jsonArray.getJSONObject(i).getString("tgt_2"));
                allDirectory.setPosted_by(jsonArray.getJSONObject(i).getString("posted_by"));
                allDirectory.setMainTitle_value(jsonArray.getJSONObject(i).getString("script"));
                allDirectory.setMain_subTitle_value(jsonArray.getJSONObject(i).getString("exchange"));
                allDirectory.setRating_value(jsonArray.getJSONObject(i).getString("rating"));
                allDirectory.setReview_value(jsonArray.getJSONObject(i).getString("review"));
                imagepath = jsonArray.getJSONObject(i).getString("advisor_image");
                Log.d("Comminh Image ", "" + jsonArray.getJSONObject(i).getString("advisor_image"));
                allDirectory.setImage1(jsonArray.getJSONObject(i).getString("advisor_image"));
                allDirectory.setImage2(jsonArray.getJSONObject(i).getString("script_image"));
                allDirectory.setBuy(jsonArray.getJSONObject(i).getString("buy_sentiment"));
                allDirectory.setSell(jsonArray.getJSONObject(i).getString("sell_sentiment"));
                allDirectory.setRecommend(jsonArray.getJSONObject(i).getString("recommendation"));
                allDirectory.setPosted_date(jsonArray.getJSONObject(i).getString("posted_date"));
                allDirectory.setCall_id(jsonArray.getJSONObject(i).getString("call_id"));
                allDirectory.setExpiry_date(jsonArray.getJSONObject(i).getString("expiry_date"));
                allDirectory.setBroker_name(jsonArray.getJSONObject(i).getString("name"));
                allDirectory.setCall_detail(jsonArray.getJSONObject(i).getString("detail"));
                allDirectory.setProgress_indicator(0);
                catListDao.add(allDirectory);
            }
            catListDao1 = catListDao;
            adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

public class FetchAllData extends AsyncTask<Void, Void, String> {
    ProgressDialog pDialog;
    int typeId;
    private Context cont;

    public FetchAllData(Context con, int typeId) {
        // TODO Auto-generated constructor stub
        this.cont = con;
        this.typeId = typeId;
        Log.d("Constructor Called", "yes");
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        if (!swipeRefreshLayout.isRefreshing()) {
            if (progressBar != null) {
                progressBar.setVisibility(View.VISIBLE);
                set.start();
            }
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        return getString();
    }

    private String getString() {
        // TODO Auto-generated method stub

        URL obj = null;
        HttpURLConnection con = null;
        try {
            obj = new URL(Constants.AppBaseUrl + "/call_listing/" + typeId);
            String userPassword = "rickmams" + ":" + "advisor11";
            String header = "Basic " + new String(android.util.Base64.encode(userPassword.getBytes(), android.util.Base64.NO_WRAP));
            con = (HttpURLConnection) obj.openConnection();
            con.addRequestProperty("Authorization", header);
            con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            con.setRequestMethod("POST");

            // For POST only - BEGIN
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();

            os.flush();
            os.close();
            // For POST only - END

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Log.i("TAG", response.toString());
                parseJSON(response.toString());
                return response.toString();

            } else {
                Log.i("TAG", "POST request did not work.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (getActivity() == null)
            return;
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if (result != null) {
            if (progressBar != null) {
                list.setAdapter(adapter);
                //pDialog.dismiss();
                if (progressBar != null) {
                    set.end();
                    if (progressBar.getVisibility() == View.VISIBLE)
                        progressBar.setVisibility(View.GONE);
                }
                if (jsonArray.length() != 0) {
                    empty_text.setVisibility(View.GONE);
                } else empty_text.setVisibility(View.VISIBLE);
            }
        }
    }

}

}

如需完整的堆栈追踪,请移至http://pastebin.com/7FDynA05

kfgdxczn

kfgdxczn1#

我知道我迟到了,但当我看到你关于处理应用程序的大量问题时,我没有发现任何错误,但我仍然想说,请检查你是否通过每次创建一个新对象来调用任何TypeFace,因此请注解它们并运行你的代码。

ih99xse1

ih99xse12#

首先,我建议你使用任何网络库可以凌空或翻新。因为他们更有效,他们将处理调用在后台和并行没有使用异步任务。
你尝试的方式是最复杂的,因为你同时打电话。
如果需要的话,那么只在恢复时进行网络调用。其余的你可以在onCreateView中调用它。或者你甚至可以选择在开始时调用它。

xtupzzrd

xtupzzrd3#

不要在活动或片段内进行 * 繁重 * 的操作,否则每次修改用户界面时都必须管理问题(异步任务也是如此)。
你可以使用异步任务或库,比如volley,但是要有服务。一个好的教程是here

相关问题