活动泄漏? - Android

时间:2013-10-17 17:27:42

标签: java android memory-leaks android-fragments rotation

活动泄漏是我能解决当前问题的最具体的术语。如果它变成其他东西,请纠正我。

场景:我创建了一个简单的Android测试应用来解决我的问题。我有一个活动,一个添加到片段容器的片段,以及一个从源获取数据的单独线程(在测试应用中,它只是创建数据本身)并通过LocalBroadcastManager将其中继到活动中。反过来,活动使用数据来更新正在显示的片段。 注意:我在Nexus 4上使用android-support-v7-appcompat,support-v4片段,API18。

问题:当应用程序首次启动时,一切都按预期运行(此时,发送到logcat的“奇怪的东西”是正常的)。在轮换,配置更改后,问题开始发生。轮换后,“奇怪的东西”应该自己弹出;但事实并非如此。旋转后,活动检测到空片段并设置我的调试标志;在此之后,“奇怪的东西”永远不会再出现,只应出现“null frag”或“frag there”。因此,我的问题和困惑。 注意:你做的旋转越多,每个“奇怪的”语句就会得到更多的“null frag”语句。

以下是重新创建问题所需的代码:

MainActivity.java:

package com.example.myfragthreadtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends ActionBarActivity {
    public static final String DEBUG_TAG = "MainActivity";
    public static final String OUTPUT_FRAGMENT = "OUTPUT_FRAGMENT";
    public static final String SAVED_DATA = "SAVED_DATA";

    public static final String UPDATE_SENT = "UPDATE_SENT";
    public static final String UPDATE_DATA = "UPDATE_DATA";

    private int myData;
    private MyFragment outputFrag;
    private volatile boolean debugFragFlag = false;
    private MyThread myThread;

    // Create a BroadcastReceiver for updates
    private final BroadcastReceiver uiUpdateReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // Check action
            if(UPDATE_SENT.equals(action)) {
                myData = intent.getIntExtra(UPDATE_DATA, -1);
                if(myData == -1) {
                    Log.d(DEBUG_TAG, "uiUpdateReceiver: data == -1");
                    return;
                }
                updateUI(myData);
            }
        }
    };

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

        myData = -2;
        myThread = null;

        // Register broadcast receivers
        LocalBroadcastManager.getInstance(this)
                             .registerReceiver(uiUpdateReceiver,
                                               new IntentFilter(UPDATE_SENT));
    }

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

        if(findViewById(R.id.fragment_container) != null) {
            outputFrag = (MyFragment) getSupportFragmentManager()
                                      .findFragmentByTag(OUTPUT_FRAGMENT);
            if(outputFrag != null) {
                Log.d(DEBUG_TAG, "onStart: frag is there");
                return;
            }
            Log.d(DEBUG_TAG, "onStart: frag is not there");
            // Create new fragment and transaction
            outputFrag = new MyFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment
            transaction.add(R.id.fragment_container, outputFrag, OUTPUT_FRAGMENT);
            transaction.commit();
        }
        else {
            Log.e(DEBUG_TAG, "onCreate: No fragment container");
        }

        return;
    }

    @Override
    protected void onRestoreInstanceState (Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        myData = savedInstanceState.getInt(SAVED_DATA);
        outputFrag = (MyFragment) getSupportFragmentManager().findFragmentByTag(OUTPUT_FRAGMENT);
        if(outputFrag == null) {
            Log.d(DEBUG_TAG, "updateUI: null frag");
            debugFragFlag = true;
            return;
        }
        outputFrag.updateOutput(myData);
    }

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

        myThread = new MyThread(this, myData);
        myThread.start();
    }

    @Override
    protected void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt(SAVED_DATA, myData);

        return;
    }

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

        // close out the data thread
        myThread.close();

        return;
    }

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

        return super.onCreateOptionsMenu(menu);
    }

    private void updateUI(int data) {
        runOnUiThread(new Runnable() {
            public void run() {
                // Update UI
                outputFrag = (MyFragment) getSupportFragmentManager()
                                          .findFragmentByTag(OUTPUT_FRAGMENT);
                if(outputFrag == null) {
                    Log.d(DEBUG_TAG, "updateUI: null frag");
                    debugFragFlag = true;
                    return;
                }
                else if(debugFragFlag) {
                    Log.d(DEBUG_TAG, "updateUI: frag there");
                }
                else {
                    Log.i(DEBUG_TAG, "updateUI: something weird");
                }
                outputFrag.updateOutput(myData);
            }
        });

        return;
    }
}

MyFragment.java:

package com.example.myfragthreadtest;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class MyFragment extends Fragment {
    private static final String DEBUG_TAG = "MyFragment";

    // UI components for updating
    private TextView console;
    private ScrollView consoleScroller;

    public void updateOutput(int data) {
        // Update UI
        setConsoleText(data);

        return;
    }

    private void setConsoleText(int data) {
        // Check that we have the UI components we want to update
        if(console == null || consoleScroller == null) {
            Log.d(DEBUG_TAG, "setConsoleText: null views");
            return;
        }

        // Update UI
        console.setText("Data" + data);
        console.invalidate();

        consoleScroller.fullScroll(View.FOCUS_DOWN);
        consoleScroller.invalidate();
        return;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        console = null;
        consoleScroller = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.frag_layout, container, false);
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Get UI components for updating
        console = (TextView)getView().findViewById(R.id.output_console);
        consoleScroller = (ScrollView)getView().findViewById(R.id.console_scroller);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();  // Always call the superclass

        console = null;
        consoleScroller = null;

        return;
    }
}

MyThread.java:

package com.example.myfragthreadtest;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class MyThread extends Thread {
    private static final String DEBUG_TAG = "MyThread";

    private Context appContext;
    private volatile boolean run;
    private int counter;

    public MyThread(Context context) {
        this.appContext = context.getApplicationContext();
        this.run = false;
        this.counter = 0;
    }

    public MyThread(Context context, int data) {
        this.appContext = context.getApplicationContext();
        this.run = false;
        this.counter = data;
    }

    public void run() {
        run = true;

        // Keep adding 1 every second
        while (run) {
            // Send update to the UI activity
            Intent intent = new Intent();
            intent.setAction(MainActivity.UPDATE_SENT);
            intent.putExtra(MainActivity.UPDATE_DATA, counter++);
            LocalBroadcastManager.getInstance(appContext).sendBroadcastSync(intent);

            try {
                Thread.sleep(3000);
            } catch(Exception e) {
                Log.d(DEBUG_TAG, "run: Sleep Failed.");
            }
        }

        return;
    }

    // Call this from the main activity to shutdown the connection 
    public void close() {
        run = false;
        return;
    }
}

frag_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/console_scroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout 
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/output_console"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/hello_world"
            android:textSize="25sp" >
        </TextView>
    </LinearLayout>
</ScrollView>

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是我看到的logcat输出: 轮换前:

10-17 09:47:24.885: D/MainActivity(23085): onStart: frag is not there
10-17 09:47:24.905: E/MainActivity(23085): updateUI: something weird
10-17 09:47:24.935: D/libEGL(23085): loaded /system/lib/egl/libEGL_adreno200.so
10-17 09:47:24.945: D/libEGL(23085): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
10-17 09:47:24.945: D/libEGL(23085): loaded /system/lib/egl/libGLESv2_adreno200.so
10-17 09:47:24.945: I/Adreno200-EGL(23085): <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM Build: Iabe52cfaeae4c5fab1acacfe6f056ba15fa93274
10-17 09:47:24.985: D/OpenGLRenderer(23085): Enabling debug mode 0
10-17 09:47:27.898: D/MainActivity(23085): uiUpdateReceiver: data == -1
10-17 09:47:30.891: E/MainActivity(23085): updateUI: something weird
10-17 09:47:33.894: E/MainActivity(23085): updateUI: something weird
10-17 09:47:36.897: E/MainActivity(23085): updateUI: something weird

轮换后:

10-17 09:47:37.018: D/MainActivity(23085): onStart: frag is there
10-17 09:47:37.038: D/MainActivity(23085): updateUI: null frag
10-17 09:47:37.038: E/MainActivity(23085): updateUI: something weird
10-17 09:47:40.011: D/MainActivity(23085): updateUI: null frag
10-17 09:47:40.011: E/MainActivity(23085): updateUI: something weird
10-17 09:47:43.014: D/MainActivity(23085): updateUI: null frag
10-17 09:47:43.014: E/MainActivity(23085): updateUI: something weird
10-17 09:47:46.017: D/MainActivity(23085): updateUI: null frag
10-17 09:47:46.017: E/MainActivity(23085): updateUI: something weird

即使看到应用程序看起来一切都很好,如果有人旋转太多,我认为这可能会导致问题。

1 个答案:

答案 0 :(得分:2)

我会回答我自己的问题,仅仅是因为其他人读到这个问题。

问题实际上是在广播公司。我从未注销过它。添加:

LocalBroadcastManager.getInstance().unregisterReceiver(uiUpdateReceiver);

OnDestroy()方法中。

不知何故,我想,接收器保留了对它必要的对象/方法的引用。