此 Handler 类应该是静态的,否则可能会发生泄漏:AsyncQueryHandler

This Handler class should be static or leaks might occur:AsyncQueryHandler

提问人:Nuno Malés 提问时间:5/12/2016 最后编辑:Nuno Malés 更新时间:5/12/2016 访问量:3533

问:

处理程序引用泄漏 由于此 Handler 被声明为内部类,因此它可能会阻止外部类被垃圾回收。如果 Handler 将 Looper 或 MessageQueue 用于主线程以外的线程,则没有问题。如果 Handler 使用的是主线程的 Looper 或 MessageQueue,则需要修复 Handler 声明,如下所示:将 Handler 声明为静态类;在外部类中,实例化外部类的 WeakReference,并在实例化 Handler 时将此对象传递给 Handler;使用 WeakReference 对象对外部类的成员进行所有引用。

我需要一个解决方案!!!!

public class EMG_Activity extends AppCompatActivity {

    // An object that manages Messages in a Thread
    public static Handler HandlerMessager;
    private static AsyncQueryHandler queryHandler;

    private static final String EMG = "EMG";
    private ManageConnectedSocket manageConnectedSocket;
    private Thread manageThread;
    private Button button_start_pause;


    private int id =  0;
    private int xValue = 0;

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

        queryHandler = new AsyncQueryHandler(getContentResolver()) {

            @Override
            protected void onInsertComplete(int token, Object cookie, Uri uri) {
                if(cookie != null)
                    id = (int) ContentUris.parseId(uri);
            }
        };
              ...........

        button_start_pause = (Button) findViewById(R.id.button_start_pause);
        button_start_pause.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                ..................

                manageConnectedSocket = new ManageConnectedSocket(MainActivity.bluetoothDevice, MainActivity.samplingFrequency, new int[]{0}, new int[]{1, 0, 1, 1});
                manageThread = new Thread(manageConnectedSocket);
                manageThread.start();

                ContentValues values = getContentValuesExam (EMG, AlsrmSchema.PROGRESS, Utils.getCurrentDate());
                queryHandler.startInsert(1, id, AlsrmContract.Exam.CONTENT_URI, values);

                ......
            }
        });
    }

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

        .....

            ContentValues values = getContentValuesExam (EMG, AlsrmSchema.CORRUPTED, Utils.getCurrentDate());
            queryHandler.startUpdate(1, null, AlsrmContract.Exam.CONTENT_URI, values, AlsrmSchema.id + " = ? ", new String[]{"" + id});
        }
    }
}
Android 警告

评论


答: 暂无答案