我怎样才能对我的活动执行asynctask?

时间:2017-12-01 09:53:11

标签: java android performance android-asynctask

您好我是Android开发中的新手,也是Stack Overflow的新手。我很好地理解了Tutorial中asynctask的概念。但我仍然感到困惑,我如何在现有代码上使用asynctask。

我正在使用 Json 从我的服务器获取数据。所以基本上我的应用程序执行一些数据获取和显示布局。我想使用asynctask,因为在 logcat 我的应用程序的 Choreographer 一直告诉我 250帧跳过,我的应用程序冻结了几秒钟。所以,基本上我的UI线程正忙于这一点并且它发生了。

  

我有两个活动

     

1)主要活动

     

2)团队活动

我在我的活动中使用导航抽屉。在导航中我有项目列表中的团队。

我的主要活动代码:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{


private boolean doubleBackToExitPressedOnce;
private Handler mHandler = new Handler();

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


}

private final Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        doubleBackToExitPressedOnce = false;
    }
};

@Override
protected void onDestroy()
{
    super.onDestroy();

    if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}


@Override
public void onBackPressed(){
   // DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    mHandler.postDelayed(mRunnable, 2000);


}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.nav_drawer, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();
    if(id == R.id.action_settings){
        return true;
    }
    return super.onOptionsItemSelected(menuItem);

}

public boolean onNavigationItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();
    if(id == R.id.home1){
        Intent searchIntent = new Intent(MainActivity.this,Home.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.service1){
        Intent searchIntent = new Intent(MainActivity.this,OurService.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.team1){
        Intent searchIntent = new Intent(MainActivity.this,Team.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.port1){
        Intent searchIntent = new Intent(MainActivity.this,OurPort.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.price1){
        Intent searchIntent = new Intent(MainActivity.this,Price.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.contact1){
        Intent searchIntent = new Intent(MainActivity.this,Contact.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.location){
        Intent searchIntent = new Intent(MainActivity.this,OurLocation.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.facebook){
        Intent searchIntent = new Intent(MainActivity.this,OurFacebook.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.linkedin){
        Intent searchIntent = new Intent(MainActivity.this,OurLinkedin.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}
}

我的团队活动代码:

public class Team extends AppCompatActivity { 

private RecyclerView recyclerView;
private TeamAdapter adapter;
private List<TeamAlbum> albumList;
private TeamAlbum teamAlbum;
ProgressDialog pd;


@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_team);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    final CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

    initViews();

}
    public class GridSpacingItemDecoration extends 
    RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }


}


private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

@Override
public void onBackPressed(){
  Intent intent = new Intent(this,MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    return;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();

    if(id == R.id.action_settings){

        return true;
    }
    return super.onOptionsItemSelected(menuItem);

}


private void initViews(){


    pd = new ProgressDialog(this);
    pd.setMessage("Fetching Data....");
    pd.setCancelable(false);
    pd.show();

    try {
        Glide.with(this).load(R.drawable.te).into((ImageView) findViewById(R.id.backdrop));
    } catch (Exception e) {
        e.printStackTrace();
    }
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    albumList = new ArrayList<>();
    adapter = new TeamAdapter(this, albumList);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

    loadJSON();

}

private  void loadJSON(){




    try{
        Client client = new Client();
        Service service = client.getClient().create(Service.class);

        Call<TeamResponse> call = service.getAlbums();
        call.enqueue(new Callback<TeamResponse>() {
            @Override
            public void onResponse(Call<TeamResponse> call, Response<TeamResponse> response) {
                List<TeamAlbum> iteams = response.body().getAlbums();
                recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), iteams));
                pd.dismiss();
            }

            @Override
            public void onFailure(Call<TeamResponse> call, Throwable t) {
                Log.d("Error", t.getMessage());
                Toast.makeText(Team.this,"Error Fetching Data!", Toast.LENGTH_SHORT).show();
                pd.dismiss();

            }
        });
    }
    catch (Exception e){
        Log.d("Error", e.getMessage());
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }

}
}
  

所以,我的团队活动中有两种方法

     

1。 initViews()    2. loadJson()

因此,正如您在我的代码中看到的那样,我在 initViews()方法和 initViews()中调用 loadJson()方法 onCreate()我的活动。

但我不知道如何在这两种方法中使用asynctask。

请有人帮助我如何实施asynctask解释。在此先感谢。

2 个答案:

答案 0 :(得分:1)

可能是这样的,如果您需要更多澄清,请告诉我

class FantasticAsyncTask extends AsyncTask<Void, Void, TeamResponse> {

    @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(YourActivity.this);
        pd.setMessage("Fetching Data....");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected TeamResponse doInBackground(final Void... voids) {
        Service service = client.getClient().create(Service.class);
        Call<TeamResponse> call = service.getAlbums();
        TeamResponse response = call.execute();
        return response;
    }

    @Override
    protected void onPostExecute(final TeamResponse response) {
        List<TeamAlbum> iteams = response.body().getAlbums();
        recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), iteams));
        pd.dismiss();
    }
}

答案 1 :(得分:1)

class LoadAlbumsAsync extends AsyncTask<Void, Void, List<TeamAlbum>>{

 @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(this);
    pd.setMessage("Fetching Data....");
    pd.setCancelable(false);
    pd.show();
    }

    @Override
    protected List<TeamAlbum> doInBackground(Void... voids) {
        Client client = new Client();
        Service service = client.getClient().create(Service.class);

// Note: modify getAlbums() retrofit method to return the TeamResponse obj directly.
        TeamResponse response = service.getAlbums();
        return response.getAlbums();
    }

@Override
protected void onPostExecute(List<TeamAlbum> list) {
    recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), list));
    pd.dismiss();
}

}

private  void loadJSON(){
       new LoadAlbumsAsync().execute();
}

希望这会有所帮助..