處理程序引用泄漏由於此Handler被聲明爲內部類,因此可能會阻止外部類被垃圾收集。如果處理程序對主線程以外的線程使用Looper或MessageQueue,則沒有問題。如果Handler使用主線程的Looper或MessageQueue,則需要修復Handler聲明,如下所示:將Handler聲明爲靜態類;在外部類中,實例化WeakReference到外部類並在實例化Handler時將此對象傳遞給Handler;使用WeakReference對象創建對外部類成員的所有引用。此Handler類應該是靜態的或可能發生泄漏:AsyncQueryHandler
我需要一個解決方案!!!!!
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});
}
}
}
我的警告是AsyncQueryHandler –
這也適用於AsyncQueryHandler –
@shriduttkothari是不是更安全的實例化來自調用者類的弱引用?更改爲'私人最終MyHandler mHandler =新MyHandler(新WeakReference <>(this));' – hannunehg