应用程序可能在其主要线程上做了太多工作 - Android Gridview

时间:2015-07-10 12:34:40

标签: android multithreading

您好我正在创建一个显示图像的网格视图。我按照指南进行操作:http://javatechig.com/android/download-and-display-image-in-android-gridview

当我在android studio中运行我的代码时,我在logcat中收到了这些错误,我不知道如何修复:

07-10 12:21:30.057    5394-5394/com.javatechig.gridviewexample I/Choreographer﹕ Skipped 135 frames!  The application may be doing too much work on its main thread.
07-10 12:21:30.588    5394-5406/com.javatechig.gridviewexample W/art﹕ Suspending all threads took: 26.488ms
07-10 12:21:30.646    5394-5406/com.javatechig.gridviewexample I/art﹕ Background partial concurrent mark sweep GC freed 588(77KB) AllocSpace objects, 5(176KB) LOS objects, 28% free, 10MB/14MB, paused 22.319ms total 36.654ms
07-10 12:21:31.984    5394-5394/com.javatechig.gridviewexample I/Choreographer﹕ Skipped 85 frames!  The application may be doing too much work on its main thread.
07-10 12:21:32.650    5394-5401/com.javatechig.gridviewexample W/art﹕ Suspending all threads took: 396.475ms
07-10 12:21:32.697    5394-5394/com.javatechig.gridviewexample I/Choreographer﹕ Skipped 38 frames!  The application may be doing too much work on its main thread.
07-10 12:21:33.120    5394-5406/com.javatechig.gridviewexample W/art﹕ Suspending all threads took: 9.729ms
07-10 12:21:35.202    5394-5394/com.javatechig.gridviewexample I/Choreographer﹕ Skipped 129 frames!  The application may be doing too much work on its main thread.
07-10 12:21:36.205    5394-5394/com.javatechig.gridviewexample I/Choreographer﹕ Skipped 36 frames!  The application may be doing too much work on its main thread.
07-10 12:23:32.286    5394-5401/com.javatechig.gridviewexample W/art﹕ Suspending all threads took: 10.405ms
07-10 12:25:23.268    5394-5401/com.javatechig.gridviewexample W/art﹕ Suspending all threads took: 5.947ms

这是我的代码:

package com.javatechig.gridviewexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GridViewActivity extends ActionBarActivity {
    private static final String TAG = GridViewActivity.class.getSimpleName();

    private GridView mGridView;
    private ProgressBar mProgressBar;

    private GridViewAdapter mGridAdapter;
    private ArrayList<GridItem> mGridData;
    private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gridview);

        mGridView = (GridView) findViewById(R.id.gridView);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

        //Initialize with empty data
        mGridData = new ArrayList<>();
        mGridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, mGridData);
        mGridView.setAdapter(mGridAdapter);

        //Grid view click event
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                //Get item at position
                GridItem item = (GridItem) parent.getItemAtPosition(position);

                Intent intent = new Intent(GridViewActivity.this, DetailsActivity.class);
                ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);

                // Interesting data to pass across are the thumbnail size/location, the
                // resourceId of the source bitmap, the picture description, and the
                // orientation (to avoid returning back to an obsolete configuration if
                // the device rotates again in the meantime)

                int[] screenLocation = new int[2];
                imageView.getLocationOnScreen(screenLocation);

                //Pass the image title and url to DetailsActivity
                intent.putExtra("left", screenLocation[0]).
                        putExtra("top", screenLocation[1]).
                        putExtra("width", imageView.getWidth()).
                        putExtra("height", imageView.getHeight()).
                        putExtra("title", item.getTitle()).
                        putExtra("image", item.getImage());

                //Start details activity
                startActivity(intent);
            }
        });

        //Start download
        new AsyncHttpTask().execute(FEED_URL);
        mProgressBar.setVisibility(View.VISIBLE);
    }


    //Downloading data asynchronously
    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            try {
                // Create Apache HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
                int statusCode = httpResponse.getStatusLine().getStatusCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    String response = streamToString(httpResponse.getEntity().getContent());
                    parseResult(response);
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }

            return result;
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Lets update UI

            if (result == 1) {
                mGridAdapter.setGridData(mGridData);
            } else {
                Toast.makeText(GridViewActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
            }

            //Hide progressbar
            mProgressBar.setVisibility(View.GONE);
        }
    }


    String streamToString(InputStream stream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        String line;
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

        // Close stream
        if (null != stream) {
            stream.close();
        }
        return result;
    }

    /**
     * Parsing the feed results and get the list
     *
     * @param result
     */
    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("posts");
            GridItem item;
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                String title = post.optString("title");
                item = new GridItem();
                item.setTitle(title);
                JSONArray attachments = post.getJSONArray("attachments");
                if (null != attachments && attachments.length() > 0) {
                    JSONObject attachment = attachments.getJSONObject(0);
                    if (attachment != null)
                        item.setImage(attachment.getString("url"));
                }
                mGridData.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
你可以告诉我该如何解决这个问题? 感谢

1 个答案:

答案 0 :(得分:1)

关于模拟器警告:The application may be doing too much work on its main thread.是正常的。忽略这些警告。