Android处理程序泄漏

时间:2015-09-24 09:47:30

标签: java android handler

在我的Android应用程序中,我正在向联系人发送消息..它显示“此处理程序类应该是静态的,否则可能是泄漏”。我的应用程序在移动电话中崩溃,但它正在使用模拟器,我正在给出下面的代码请通过它,如果有人可以提供任何帮助请帮助..

 progresshandler = new Handler()
        {
            public void handleMessage(Message msg)
            {
                //progressDialog.dismiss();
                //Toast.makeText(SendMessagesActivity.this, "Messages Sent",Toast.LENGTH_LONG).show();
                new ProgressTask().execute();

            }
        };

1 个答案:

答案 0 :(得分:1)

为避免泄漏,Handler创建扩展Handler类的Custom类,如下所示:

 // Handler of incoming messages from clients.

    private static class IncomingHandler extends Handler {
        private WeakReference<YourActivity> yourActivityWeakReference;

        public IncomingHandler(YourActivity yourActivity) {
            yourActivityWeakReference = new WeakReference<>(yourActivity);
        }

        @Override
        public void handleMessage(Message message) {
            if (yourActivityWeakReference != null) {
                YourActivity yourActivity = yourActivityWeakReference.get();

Edited :          new ProgressTask().execute(); 
//                switch (message.what) {
//                }
            }
        }
    }

创建此类的对象,无论您想在何处使用,如下所示。

     private IncomingHandler mPulseHandler;
     mPulseHandler = new IncomingHandler(HomeActivity.this);
     mPulseHandler.sendEmptyMessage(0);

编辑:

IncomingHandler progresshandler = new IncomingHandler(YourActivity.this);
        if (editMessage.getText().toString().length() > 0) {
            SendMessagesThread thread = new SendMessagesThread(progresshandler);
            thread.start(); 
            // progressDialog.show();
        }

编辑:

  1. 在您的活动中声明此任务:

    private ProgressTask progressTask;

  2. 在onCreate()

    中创建它的实例

    progressTask = new ProgressTask();

  3. 更改IncomingHandler中的行:

    yourActivity.progressTask.execute();

  4. 由于