处理程序内存泄漏?

时间:2015-01-08 19:37:04

标签: java android memory-leaks

我有一个在主线程上声明的Handler:

  mainHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {

                    case 1:

                        Bundle bundle = msg.getData();
                        mTextView.setText(bundle.getString("message"));
                        break;

                    . . .

                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };

其中mTextView是在onCreate()上定义的TextView。

我有一个在单独的线程中使用的任务。 runnable从主线程存储mainHandler并告诉它发送消息:

public class SomeRunnable implements Runnable {

    private Handler mHandler;

    public SomeRunnable(Handler handler) throws IOException {
        . . .    
        mHandler = handler;
    }

    @Override
    public void run() {

        while (!Thread.currentThread().isInterrupted()) {
            try {
                    . . .

                    Message msg = mHandler.obtainMessage();
                    . . .
                    mHandler.sendMessage(msg);
                }

            } catch (IOException e) {
                Log.e("Error", e.hashCode() + ": " + e.getLocalizedMessage());
            }
        }
    }

我已经看到,如果Handler类不是静态的,可以使用Handler#postDelayed()之类的方法来创建内存泄漏。但是,我正在使用Handler#sendMessage(),它会立即将消息放入消息队列中。

我是否还有内存泄漏的危险?即使有:

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

        mThread.interrupt();
        mainHandler.removeCallbacksAndMessages(null);
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

要解决所有可能性,您可以mHandler WeakReference进行如下操作:

public class SomeRunnable implements Runnable {

    private WeakReference<Handler> mHandlerRef;

    public SomeRunnable(Handler handler) throws IOException {
        . . .    
        mHandlerRef = new WeakReference<Handler>( handler );
    }

    @Override
    public void run() {

        while (!Thread.currentThread().isInterrupted()) {
            try {
                    . . .
                    Handler mHandler = mHandlerRef.get();
                    if( mHandler != null ) {
                        Message msg = mHandler.obtainMessage();
                        . . .
                        mHandler.sendMessage(msg);
                    }
                }

            } catch (IOException e) {
                Log.e("Error", e.hashCode() + ": " + e.getLocalizedMessage());
            }
        }
    }
}