Android Async Task冻结UI

时间:2016-04-05 07:06:55

标签: android android-asynctask android-viewflipper

您好我有一个用户点击TAB后打开的用户。实际上我有一个ViewGroup和Tabactivity作为主要活动。在第一个标签上我有三个活动。

现在,在一个活动中,我使用AsyncTask在Onresate上填充了一个列表视图(自定义)和一个ViewFlipper(仅添加视图)。

在Pre Execute中的asynctask中,如果我为loader添加代码,则会出错。此外,如果我没有显示加载程序,屏幕将冻结,直到异步任务完成。

我实际上想先加载列表视图,然后在后台使用加载程序运行异步任务。也不想冻结屏幕。

这是我的活动

package thai.phrasi.ctech.com.phrasi;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;


public class WordActivity extends ActionBarActivity {

    categories category_obj;
    word word_obj;
    wordDB wordDb;
    WordAdapter adapter;
    MediaPlayer mPlayer;
    boolean doubleBackToExitPressedOnce = false;
    public static ViewFlipper viewFlipper;
    public View view;
    private static ProgressDialog pleaseWaitDialog;

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

        viewFlipper = new ViewFlipper(this);
        viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));



        TextView txt = (TextView) findViewById(R.id.phraseListHeading);
        Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");

        String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();

        wordDb = new wordDB(getApplicationContext());
        getAllWords();

        //asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
        //task2.execute();


        txt.setTypeface(font);
        txt.setText(categoryName);


        ListView wordListView;
        wordListView = (ListView)findViewById(R.id.list_view_word);
        wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Object o = parent.getItemAtPosition(position);
                word_obj = (word) o;
                if(Integer.valueOf(word_obj.getCategoryId())>=0) {
                    Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
                    myIntent.putExtra("word_obj", word_obj);
                    myIntent.putExtra("position",position);
                    myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
                    myIntent.putExtra("favouriteFlag",0);
                    myIntent.putExtra("searchFlag",0);
                    myIntent.putExtra("searchString", "");
                    WordActivity.this.startActivity(myIntent);


                }

            }
        });

        ImageView backButton = (ImageView) findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
                View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
                FirstGroup.group.replaceView(vw);
                viewFlipper.removeAllViews();
                System.runFinalization();
                Runtime.getRuntime().gc();
                System.gc();
            }
        });


    }

    @Override
    protected void onPause() {
        super.onPause(); // Don't forget this line
        stop();
    }

    public void stop(){
        mPlayer=adapter.getMPlayerInstace();
        if(mPlayer!=null){
            mPlayer.stop();
            mPlayer.release();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_word, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onResume(){
        super.onResume();

        new Thread(new Runnable() {
            public void run(){
                //All your heavy stuff here!!!
                category_obj = (categories) getIntent().getSerializableExtra("category_obj");
                if(viewFlipper.getChildCount() == 0) {
                    asyncFlipperView task = new asyncFlipperView(getApplicationContext());
                    task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
                }
            }
        }).start();



    }


    public void getAllWords(){

        category_obj = (categories) getIntent().getSerializableExtra("category_obj");
        ArrayList<word> words = new ArrayList<word>();
        Cursor row =  wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
        words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
        words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
        row.moveToFirst();
        while (!row.isAfterLast()) {
            //Log.d("Data id: ", row.getString(2));
            words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
            row.moveToNext();
        }
        row.close();

        adapter = new WordAdapter(WordActivity.this, words);

        ListView listView = (ListView) findViewById(R.id.list_view_word);
        listView.setAdapter(adapter);

    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

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

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Double tap back button to exit.");

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();


        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }




    public class asyncLoadWordList extends  AsyncTask<ArrayList<word>, Void, ArrayList<word>>{


        private Context mContext;
        public asyncLoadWordList(Context context) {
            mContext = context;

        }


        protected void onPreExecute() {
            //Start the splash screen dialog
           /* if (pleaseWaitDialog == null)
                pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
                        "PLEASE WAIT",
                        "Getting results...",
                        false);
                        */

        }



        @Override
        protected ArrayList<word> doInBackground(ArrayList<word>... params) {

            wordDb = new wordDB(mContext);
            category_obj = (categories) getIntent().getSerializableExtra("category_obj");
            ArrayList<word> words = new ArrayList<word>();
            Cursor row =  wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
            words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
            words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
            row.moveToFirst();
            while (!row.isAfterLast()) {
                //Log.d("Data id: ", row.getString(2));
                words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
                row.moveToNext();
            }
            row.close();

            return words;
        }
        protected void onPostExecute(ArrayList<word> result) {

            adapter = new WordAdapter(WordActivity.this, result);

            ListView listView = (ListView) findViewById(R.id.list_view_word);
            listView.setAdapter(adapter);


            if (pleaseWaitDialog != null) {
                pleaseWaitDialog.dismiss();
                pleaseWaitDialog = null;

            }


            asyncFlipperView task = new asyncFlipperView(getApplicationContext());
            task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
        }
    }

    public class asyncFlipperView extends AsyncTask<String, Void, String[]> {


        String categoryId;
        private Context mContext;
        wordDB wordDb;
        Cursor row;
        JSONObject json;
        View view;

        //private ProgressDialog dialog = new ProgressDialog(WordActivity.this);

        public asyncFlipperView(Context context) {
            mContext = context;
        }


        protected void onPreExecute() {
            //Start the splash screen dialog


        }

        @Override
        protected String[] doInBackground(String... params) {

            categoryId = params[0];


            json = new JSONObject();
        /*do application level task*/
            GlobalState state = ((GlobalState) mContext);
            state.doAction();
        /*Ends*/

            wordDb = new wordDB(mContext);
            row = wordDb.selectWordList(categoryId);
            Log.d("Tag: search result", row.getString(2).toString());
            return new String[]{categoryId};
        }

        protected void onPostExecute(String[] result) {

            categoryId = result[0];
            ImageView phraseImage = null;
            Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
            row.moveToFirst();
            while (!row.isAfterLast()) {


            /*phrase Image*/
                Integer fileNameLength = row.getString(5).toString().length();
                String fileName = row.getString(5).toString();
                String imageFile = fileName.substring(0, fileNameLength - 4);

                //viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
                LayoutInflater inflater = getLayoutInflater();
                view = inflater.inflate(R.layout.word_details_flipper_view, null);

                TextView tv = (TextView) view.findViewById(R.id.text_english);
                tv.setTypeface(font);
                tv.setText(row.getString(2).toString());


                String picName = row.getString(6).toString();
                picName = picName.replace(".png", "");

                Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
                ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
                Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);

                TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
                tvTranslated.setTypeface(font);
                tvTranslated.setText(row.getString(3).toString());

                TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
                pronounce.setTypeface(font);
                pronounce.setText(row.getString(4).toString());

                phraseImage = (ImageView) view.findViewById(R.id.phrase_image);

                Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
                Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);

                view.setTag(R.string.csvId, row.getString(0).toString());
                viewFlipper.addView(view);
                row.moveToNext();
            }
            row.close();


        }

        private Context getDialogContext() {
            Context context;
            if (getParent() != null) context = getParent();
            else context = WordActivity.this;
            return context;
        }


    }


}

0 个答案:

没有答案