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

时间:2016-05-12 13:32:53

标签: android warnings

处理程序引用泄漏由于此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});
        }
    }
}

0 个答案:

没有答案