Android中的每次重新加载意图都会增加内存使用量。为什么?

时间:2016-12-23 10:34:48

标签: android memory bitmap

我有一个活动/意图,其中从设备读取文本文件(包含JSON数组)。 在每次重新加载时,数组中的另一行正在进行处理。 文本文件不是很大(20 Kb),而是在MainActivity中下载,还有一些图像(最多50个),介于20到70 Kb之间。

每次重新加载intent并且另一行是进程时,另一个图像被加载到ImageView中。另外几个TextViews使用从JSON数组中读取的字符串进行更新。

问题在于,每次重新加载意图时,内存使用量都会增加大约1 Mb。

我通过使用:

来证明这一点
Runtime runtime = Runtime.getRuntime();
long usedMemory=runtime.totalMemory() / (1024 * 1024);

Bitmap被回收, BufferedWriter已关闭, FileInputStream已关闭, BufferedReader已关闭 InputStreamReader已关闭

我错过了什么导致内存使用量增加?

这是活动的代码形式:

public class LoadRaaplijstActivity extends AppCompatActivity {

    private TextView locatieText;
    private TextView totaalText;
    private TextView inhoudText;
    private TextView descriptionText;
    private TextView eanText;
    private TextView ditpadText;
    private TableLayout layout16;
    private TableLayout layout32;
    private Button raapbuttonNext;

    private Menu menu;
    private Toast toast;

    private String next;
    private String prev;
    private String deze;
    private String ean;
    private String foto;
    private String description;
    private String voorraad;
    private String totaal;
    private String inhoud;
    private JSONArray bakken;
    private int aantalbakken;
    private String einde = "";
    private String loadeinde = "0";
    private String picked;
    private String locatie;
    private String locatiepadclean;
    private String locatiemeterclean;
    private String locatieplankclean;
    private String locatievakjeclean;
    private String pijl;
    private String totaalditpad;

    private String batch;
    private String kar;
    private String raper;
    private String afmaken;

    String spinneridSelected;
    String spinnerkarSelected;
    String spinnerraperSelected;
    String radioAfmakenSelected;

    Bitmap myBitmap;

    ArrayList<Integer> gehadArray = new ArrayList<Integer>();


    //JSON array
    private JSONArray raaplijstresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

        setContentView(R.layout.activity_load_raaplijst);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        findViewById(R.id.productimage).setVisibility(View.GONE);
        findViewById(R.id.wificonnectie).setVisibility(View.GONE);
        findViewById(R.id.probeeropnieuw).setVisibility(View.GONE);
        findViewById(R.id.raapbuttonNext).setVisibility(View.VISIBLE);
        findViewById(R.id.raapbuttonPrev).setVisibility(View.VISIBLE);

        raapbuttonNext     = (Button) findViewById(R.id.raapbuttonNext);
        raapbuttonNext.setFocusable(true);
        raapbuttonNext.setFocusableInTouchMode(true);
        raapbuttonNext.requestFocus();

        locatieText     = (TextView) findViewById(R.id.locatieText);
        totaalText      = (TextView) findViewById(R.id.totaalText);
        inhoudText      = (TextView) findViewById(R.id.inhoudText);
        eanText         = (TextView) findViewById(R.id.eanText);
        ditpadText      = (TextView) findViewById(R.id.ditpadTxt);
        descriptionText = (TextView) findViewById(R.id.descriptionText);
        layout16 = (TableLayout) findViewById(R.id.layout16);
        layout32 = (TableLayout) findViewById(R.id.layout32);

        Intent intent = getIntent();

        spinneridSelected = intent.getStringExtra("spinneridSelected");
        spinnerkarSelected = intent.getStringExtra("spinnerkarSelected");
        spinnerraperSelected = intent.getStringExtra("spinnerraperSelected");
        radioAfmakenSelected = intent.getStringExtra("radioAfmakenSelected");
        deze = intent.getStringExtra("load");

        batch   = spinneridSelected;
        kar     = spinnerkarSelected;
        raper   = spinnerraperSelected;
        afmaken = radioAfmakenSelected;

        if(afmaken.equals("ja")){

            deze = getLaatstgehad();
        }

        Integer gehad = Integer.parseInt(deze.toString());

        gehadArray = intent.getIntegerArrayListExtra("gehadArray");

        if(!gehadArray.contains(gehad)) {
            try {
                gehadArray.add(gehad);
            } catch (NumberFormatException nfe) {
                System.out.println("Could not parse " + nfe);
            }
        }else{
            locatieText.setTextColor(Color.GREEN);
        }

        saveGehad();

        getRaaplijstRegel();

    }

    private void saveGehad() {
        File root = android.os.Environment.getExternalStorageDirectory();

        File dir = new File(root.getAbsolutePath() + "/Raaplijst");

        File file = new File(dir, "/gehad.txt");
        if(file.exists()) file.delete();
        try {

            BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
            buf.write(deze.toString());
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getLaatstgehad() {
        File root = android.os.Environment.getExternalStorageDirectory();

        File dir = new File(root.getAbsolutePath() + "/Raaplijst");

        File file = new File(dir, "/gehad.txt");
        String ret = deze;
        if(file.exists()){
            try {
                FileInputStream inputStream = new FileInputStream (file);

                if ( inputStream != null ) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String receiveString = "";
                    StringBuilder stringBuilder = new StringBuilder();

                    while ( (receiveString = bufferedReader.readLine()) != null ) {
                        stringBuilder.append(receiveString);
                    }
                    inputStreamReader.close();
                    bufferedReader.close();
                    inputStream.close();
                    String gehadFromFile = stringBuilder.toString();
                    ret = gehadFromFile;
                }
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            ret = deze;
        }

        return ret;
    }

    public void loadPrev (View view){
        loadRaaplijstPrev();
    }

    public void loadRaaplijstPrev (){

                if (prev.equals("-1")) {

                    Intent intent = new Intent(this, GratisProducten.class);

                    Bundle extras = new Bundle();

                    extras.putString("spinneridSelected", batch);
                    extras.putString("spinnerkarSelected", kar);
                    extras.putString("spinnerraperSelected", raper);
                    extras.putString("radioAfmakenSelected", "nee");
                    extras.putIntegerArrayList("gehadArray", gehadArray);
                    intent.putExtras(extras);

                    startActivity(intent);
                    finish();

                }  else {
                    Intent intent = new Intent(this, LoadRaaplijstActivity.class);

                    Bundle extras = new Bundle();
                    extras.putString("load", prev);
                    extras.putString("spinneridSelected", batch);
                    extras.putString("spinnerkarSelected", kar);
                    extras.putString("spinnerraperSelected", raper);
                    extras.putString("radioAfmakenSelected","nee");
                    extras.putIntegerArrayList("gehadArray", gehadArray);
                    intent.putExtras(extras);

                    startActivity(intent);
                    finish();
                }        
    }

    public void loadBegin (View view){

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();

    }

    public void loadBegin(){
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    public void loadNext (View view){
        loadRaaplijstNext();
    }

    public void loadRaaplijstNext (){

                if (loadeinde.equals("1")) {
                    loadEnd();
                } else {

                    Intent intent = new Intent(this, LoadRaaplijstActivity.class);

                    Bundle extras = new Bundle();
                    extras.putString("spinneridSelected", batch);
                    extras.putString("spinnerkarSelected", kar);
                    extras.putString("spinnerraperSelected", raper);
                    extras.putString("radioAfmakenSelected","nee");
                    extras.putString("load", next);
                    extras.putIntegerArrayList("gehadArray", gehadArray);
                    intent.putExtras(extras);
                    startActivity(intent);
                    finish();
                }
    }

    public void loadEnd(){

            Intent intent = new Intent(this, EndActivity.class);
            Bundle extras = new Bundle();
            extras.putString("einde", einde);
            extras.putString("load", deze);
            extras.putString("spinneridSelected", batch);
            extras.putString("spinnerkarSelected", kar);
            extras.putString("spinnerraperSelected", raper);
            extras.putString("radioAfmakenSelected", "nee");
            extras.putIntegerArrayList("gehadArray", gehadArray);
            intent.putExtras(extras);
            startActivity(intent);
            finish();

    }

    private String readRaaplijstFromFile() {

        String ret = "Raaplijst niet gevonden";

        File root = android.os.Environment.getExternalStorageDirectory();

        File dir = new File(root.getAbsolutePath() + "/Raaplijst");

        try {
            FileInputStream inputStream = new FileInputStream (new File(dir + "/raaplijstJSON.txt"));

            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }
                inputStreamReader.close();
                bufferedReader.close();
                inputStream.close();
                ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }

    private void getRaaplijstRegel(){
            String raaplijstJson = readRaaplijstFromFile();

            if(raaplijstJson.equals("Raaplijst niet gevonden")){
            }else{

                try {
                    JSONObject j = new JSONObject(raaplijstJson);

                    raaplijstresult = j.getJSONArray(Config.JSON_ARRAY_RAAPLIJST);

                    getRegel(raaplijstresult);

                } catch (JSONException e) {StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    String stacktrace = sw.toString();
                    writeExceptionToFile(stacktrace);
                    e.printStackTrace();
                }
            }
    }

    private void getRegel(JSONArray j) {
        for (int h = 0; h < j.length(); h++) {

            try {
                JSONObject sorteerObj = j.getJSONObject(h);

                JSONArray sorteer = sorteerObj.getJSONArray("sorteer");

                int i = Integer.parseInt(deze);
                try {
                    JSONObject json = sorteer.getJSONObject(i);

                    einde = json.getString("einde");

                    loadeinde = json.getString("loadeinde");
                    if(loadeinde.equals("1")){
                        loadEnd();
                    }

                    ean = json.getString("ean");
                    eanText.setText("EAN: " + ean);

                    locatie = json.getString("locatie");
                    locatieText.setText(locatie);

                    locatiepadclean = json.getString("locatiepad");
                    if(locatiepadclean.equals("leeg")){
                        locatiepadclean = "";
                    }

                    locatiemeterclean = json.getString("locatiemeter");

                    if(locatiemeterclean.equals("leeg")){
                        locatiemeterclean = "";
                    }

                    locatieplankclean = json.getString("locatieplank");
                    if(locatieplankclean.equals("leeg")){
                        locatieplankclean = "";
                    }

                    locatievakjeclean = json.getString("locatievakje");
                    if(locatievakjeclean.equals("leeg")){
                        locatievakjeclean = "";
                    }

                    picked = json.getString("picked");

                    if(picked.equals("1")) {
                        locatieText.setTextColor(Color.GREEN);
                    }

                    foto = json.getString("foto");

                    File root = android.os.Environment.getExternalStorageDirectory();
                    File dir = new File(root.getAbsolutePath() + "/Raaplijst");
                    File imgFile = new  File(dir + "/" + foto);

                    if(imgFile.exists()){

                        if (myBitmap != null) {
                            myBitmap.recycle();
                            myBitmap = null;
                        }

                        myBitmap = decodeFile(imgFile, 231, 231);

                        ImageView bindImage = (ImageView) findViewById(R.id.productimage);

                        bindImage.setImageBitmap(myBitmap);

                    }else{
                        toast = Toast.makeText(getApplicationContext(), imgFile.toString(), Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20);
                        toast.show();
                    }

                    findViewById(R.id.loadingPanel).setVisibility(View.GONE);
                    findViewById(R.id.productimage).setVisibility(View.VISIBLE);

                    description = json.getString("description");
                    descriptionText.setText(description);

                    voorraad = json.getString("voorraad");

                    aantalbakken = Integer.parseInt(json.getString("aantalbakken"));

                    if(aantalbakken == 32){
                        findViewById(R.id.layout16).setVisibility(View.GONE);
                        findViewById(R.id.layout32).setVisibility(View.VISIBLE);
                        findViewById(R.id.layout32).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
                            public void onSwipeTop() {

                            }

                            public void onSwipeRight() {
                                loadRaaplijstPrev();
                            }

                            public void onSwipeLeft() {
                                loadRaaplijstNext();
                            }

                            public void onSwipeBottom() {

                            }

                        });
                    }else{
                        findViewById(R.id.layout32).setVisibility(View.GONE);
                        findViewById(R.id.layout16).setVisibility(View.VISIBLE);
                        findViewById(R.id.layout16).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
                            public void onSwipeTop() {

                            }

                            public void onSwipeRight() {
                                loadRaaplijstPrev();
                            }

                            public void onSwipeLeft() {
                                loadRaaplijstNext();
                            }

                            public void onSwipeBottom() {

                            }

                        });
                    }

                    int b = 0;
                    int[] textViewIds;
                    int[] bakdrawables;

                    if(aantalbakken == 32) {
                        textViewIds = new int[]{R.id.b32, R.id.b33, R.id.b34, R.id.b35, R.id.b36, R.id.b37, R.id.b38, R.id.b39,
                                R.id.b40, R.id.b41, R.id.b42, R.id.b43, R.id.b44, R.id.b45, R.id.b46, R.id.b47,
                                R.id.b48, R.id.b49, R.id.b50, R.id.b51, R.id.b52, R.id.b53, R.id.b54, R.id.b55,
                                R.id.b56, R.id.b57, R.id.b58, R.id.b59, R.id.b60, R.id.b61, R.id.b62, R.id.b63
                        };

                        bakdrawables = new int[]{R.drawable.vbbb1, R.drawable.vbbb2, R.drawable.vbbb3, R.drawable.vbbb4, R.drawable.vbbb5, R.drawable.vbbb6, R.drawable.vbbb7, R.drawable.vbbb8,
                                R.drawable.vbbb9, R.drawable.vbbb10, R.drawable.vbbb11, R.drawable.vbbb12, R.drawable.vbbb13, R.drawable.vbbb14, R.drawable.vbbb15, R.drawable.vbbb16,
                                R.drawable.vbbb17, R.drawable.vbbb18, R.drawable.vbbb19, R.drawable.vbbb20, R.drawable.vbbb21, R.drawable.vbbb22, R.drawable.vbbb23, R.drawable.vbbb24,
                                R.drawable.vbbb25, R.drawable.vbbb26, R.drawable.vbbb27, R.drawable.vbbb28, R.drawable.vbbb29, R.drawable.vbbb30, R.drawable.vbbb31, R.drawable.vbbb32
                        };
                    }else{
                        textViewIds = new int[]{R.id.b16, R.id.b17, R.id.b18, R.id.b19,
                                R.id.b20, R.id.b21, R.id.b22, R.id.b23,
                                R.id.b24, R.id.b25, R.id.b26, R.id.b27,
                                R.id.b28, R.id.b29, R.id.b30, R.id.b31
                        };

                        bakdrawables = new int[]{R.drawable.vbb1, R.drawable.vbb2, R.drawable.vbb3, R.drawable.vbb4, R.drawable.vbb5, R.drawable.vbb6, R.drawable.vbb7, R.drawable.vbb8,
                                R.drawable.vbb9, R.drawable.vbb10, R.drawable.vbb11, R.drawable.vbb12, R.drawable.vbb13, R.drawable.vbb14, R.drawable.vbb15, R.drawable.vbb16
                        };
                    }

                    for (int z = 0; z < aantalbakken; z++) {
                        String prefixbakdrawable = "vbb";

                        if(aantalbakken == 32){
                            prefixbakdrawable = "vbbb";
                        }

                        Integer inhoudBak = Integer.parseInt(json.getString("b" + z));
                        if (inhoudBak > 0) {
                            ((TextView) findViewById(textViewIds[z])).setText(inhoudBak.toString());
                            ((TextView) findViewById(textViewIds[z])).setTextColor(Color.WHITE);

                            findViewById(textViewIds[z]).setBackgroundResource(bakdrawables[z]);
                        } else {
                            ((TextView) findViewById(textViewIds[z])).setText(" ");
                        }
                    }

                    totaal = json.getString("totaal");
                    totaalText.setText(totaal);

                    inhoud = json.getString("inhoud");
                    inhoudText.setText(inhoud);

                    prev = json.getString("prev");

                    next = json.getString("next");

                    pijl = json.getString("pijl");

                    if(pijl.equals("left")){
                        locatieText.setBackgroundResource(R.drawable.left);
                    }

                    totaalditpad = json.getString("totaalditpad");
                    ditpadText.setText(totaalditpad);

                    if (sorteerObj.has("bakken")) {
                        bakken = sorteerObj.getJSONArray("bakken");
                    }

                } catch (JSONException e) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    e.printStackTrace();
                }

            } catch (JSONException e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                String stacktrace = sw.toString();
                writeExceptionToFile(stacktrace);
                e.printStackTrace();
            }
        }
    }

    public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
        try {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            final int REQUIRED_WIDTH=WIDTH;
            final int REQUIRED_HIGHT=HIGHT;
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
                scale*=2;

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);

        } catch (FileNotFoundException e) {}
        return null;
    }

    public void probeerOpnieuw (View v){
        loadAgain("ja");
    }

    public void loadAgain(String doorgaan) {

        Intent intent = new Intent(this, LoadRaaplijstActivity.class);

        Bundle extras = new Bundle();
        extras.putString("load", deze);
        extras.putString("spinneridSelected", batch);
        extras.putString("spinnerkarSelected", kar);
        extras.putString("spinnerraperSelected", raper);
        extras.putString("radioAfmakenSelected", doorgaan);
        extras.putIntegerArrayList("gehadArray", gehadArray);
        intent.putExtras(extras);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_load_raaplijst, menu);
        this.menu = menu;

        String headerTxtTxt = "Batch: " + batch + "- Kar: " + kar + "- Raper: " + raper;

        Runtime runtime = Runtime.getRuntime();
        long maxMemory=runtime.maxMemory() / (1024 * 1024);
        long usedMemory=(runtime.totalMemory() / (1024 * 1024)) - (runtime.freeMemory() / (1024 * 1024));

        if(!Config.DEBUG.equals("")) headerTxtTxt = headerTxtTxt + " MaxMem:" + maxMemory + "Mb CurMem:" + usedMemory;
        setTitle(headerTxtTxt);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.stopraaplijst:
                Intent intent = new Intent(this, MainActivity.class);

                Bundle extras = new Bundle();

                intent.putExtras(extras);
                startActivity(intent);
                finish();
                break;

            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:

                loadAgain(radioAfmakenSelected);
                return true;

            case KeyEvent.KEYCODE_VOLUME_UP:

                loadRaaplijstPrev();
                return true;

            case KeyEvent.KEYCODE_ENTER:

                loadRaaplijstNext();
                return true;

            default:
                return true;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_ENTER:
                return true;
            default:
                return true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void writeExceptionToFile(String exception){
        File root = android.os.Environment.getExternalStorageDirectory();
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(
                new Date());

        File dir = new File(root.getAbsolutePath() + "/Lograaplijst");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        Calendar c = Calendar.getInstance();

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String formattedDate = df.format(c.getTime());

        File file = new File(dir, "log_h_" + formattedDate + "_" + batch + "_" +  kar + ".txt");

        try {
            BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
            buf.append(currentDateTimeString + ":" + exception.toString());
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案