加载时活动滞后

时间:2017-05-05 23:39:13

标签: android performance android-studio android-activity

我的活动在启动时滞后(非常严重)。滞后通常持续不到一秒钟,但它很明显,我不希望它。

我不确定导致它滞后的原因,但是我需要修理它,以便它在加载时能够像黄油一样顺畅。

以下是活动:

public class ProfileActivity extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;

    private RecyclerView recyclerView;

    private LinearLayoutManager layoutManager;

    private SwipeRefreshLayout swipeRefreshLayout;

    private EndlessRecyclerViewScrollListener scrollListener;

    private int userId;

    private User user;

    private List<Object> data = new ArrayList<>();

    protected UserAdapter userAdapter;

    private TextView username, userNumPosts;
    private ImageView userBackground, userColor, userIcon;

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

        // Get userId from intent
        userId = getIntent().getExtras().getInt("userId");

        // Check if the user is in realm db
        user = getRealm().where(User.class)
                .equalTo("id", userId)
                .findFirst();

        // Make status bar black
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#000000"));
        }

        if (getSupportActionBar() != null) {
            // Change toolbar color to the user's chosen color
            getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#" + user.getColor())));

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setRefreshing(true);

        username = (TextView) findViewById(R.id.username);
        userNumPosts = (TextView) findViewById(R.id.userNumPosts);

        userBackground = (ImageView) findViewById(R.id.userBackground);
        userColor = (ImageView) findViewById(R.id.userColor);
        userIcon = (ImageView) findViewById(R.id.userIcon);

        username.setText(user.getUsername());
        userNumPosts.setText(user.getNumPosts());

        userColor.setBackgroundColor(Color.parseColor("#" + user.getColor()));

        // Add the user icon
        Glide.with(this)
                .load(user.getIcon())
                .into(userIcon);

        // Add the user background
        Glide.with(this)
                .load(user.getBackgroundImage())
                .into(userBackground);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setNestedScrollingEnabled(false);

        layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        userAdapter = new UserAdapter(this, data);
        recyclerView.setAdapter(userAdapter);

        userAdapter.setUserAdapterListener(new UserAdapter.UserAdapterListener() {
            @Override
            public void onRequestRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                getUserData(1);
            }
        });

        scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
            @Override
            public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
                getUserData(page);
            }
        };

        recyclerView.addOnScrollListener(scrollListener);

        getUserData(1);
    }

    public void getUserData(final int page) {
        ApiInterface apiService = ApiClient.createService(ApiInterface.class, userAuthToken);

        Call<BasicResponse> call = apiService.getUserData(userId, page);
        call.enqueue(new Callback<BasicResponse>() {
            @Override
            public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
                if (response.isSuccessful()) {
                    // Show the data

                    List<Message> messageData = response.body().getData();

                    data.addAll(messageData);

                    userAdapter.notifyDataSetChanged();
                }

                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<BasicResponse> call, Throwable t) {
                // 
            }
        });
    }
}

什么可能导致我的活动在加载时滞后?我应该将所有主要代码放在onCreate()吗?

2 个答案:

答案 0 :(得分:1)

onCreate()中有太多进程。尝试将某些方法移至onResume()。换句话说,您正在使用数据处理阻止UI。然后,在布局中,请尽量减少嵌套布局的使用。如果布局有很多孩子,应用程序将渲染速度变慢。还要考虑在数据之前设计/加载UI。这将允许您的用户看到某些内容,即使它不完整。

P / s:考虑将您的数据/流程移至AsyncTask。或Thread

答案 1 :(得分:0)

我也在寻找解决方案,这对我有用

overridePendingTransition(0,0);

在开始滞后活动之前。