0

活动泄漏是针对当前问题我能想到的最具体的术语。如果它变成了别的东西,请纠正我。

场景:我创建了一个简单的 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>

活动主.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

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

4

1 回答 1

2

我会回答我自己的问题,只是为了其他人读到这个的罕见情况。

问题实际上出在广播公司。我从来没有注销它。通过增加:

LocalBroadcastManager.getInstance().unregisterReceiver(uiUpdateReceiver);

OnDestroy()方法中。

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

于 2013-10-30T17:41:49.763 回答