我有一个EventBus()
运行并循环运行,直到我的应用程序启动时到达我的另一个Fragment
。当我将应用程序闲置至少30 ++分钟时,我得到了以下堆栈跟踪:
10-11 10:23:46.315 3790-4797/com.jti.mikee.jti_pos W/libc: pthread_create failed: couldn't allocate 1040384-byte stack: Out of memory
10-11 10:23:46.315 3790-4797/com.jti.mikee.jti_pos E/dalvikvm: pthread_create (stack size 16384 bytes) failed: Try again
我还在ScheduleExecutorService()
上使用onCreateView()
scheduledExecutorService = Executors.newScheduledThreadPool(4);
这是我的EventBus()
public static final Runnable mRunnable = new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(new EB_TapCard());
}
};
在我的onResume()
上是代码
@Override
public void onResume() {
Log.e("current_module",current_module);
super.onResume();
try {
EventBus.getDefault().register(this);
rfscanner = scheduledExecutorService.scheduleAtFixedRate(mRunnable, 0, 2, TimeUnit.SECONDS);
} catch (Throwable e) {
e.printStackTrace();
}
}
最后,这是我的onPause()
方法
@Override
public void onPause() {
try {
getContext().unregisterReceiver(broadcastReceiver);
} catch (Throwable e) {
e.printStackTrace();
}
rfscanner.cancel(true);
EventBus.getDefault().unregister(this);
super.onPause();
}
我想知道当我闲置设备时,可运行设备仍在运行。如何暂停/恢复?非常感谢。
编辑
到目前为止,我已经尝试添加一个函数Callback()
。它工作正常,但是在我点击卡后,读卡器无法读取第二张卡。如何在不使内存变满的情况下使其循环?
class CallBackThread extends Thread {
@Override
public void run() {
try {
RFCardInterface.waitForCardPresent(RFCardInterface.CONTACTLESS_CARD_MODE_AUTO, 1, -1);
if (RFCardInterface.isCallBackCalled &&
RFCardInterface.notifyEvent.eventID == RFCardInterface.CONTACTLESS_CARD_EVENT_FOUND_CARD) {
IDCatcher = StringUtility.ByteArrayToString(RFCardInterface.notifyEvent.eventData,
RFCardInterface.notifyEvent.eventData.length);
IDCatcher = IDCatcher.substring(9, 21).replace(" ", "");
Log.e("IDCatcher", IDCatcher);
EventBus.getDefault().post(new EBTest2());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
尝试以下方法:
private Handler mHandler; // the handler to this activity
private Runnable mCallback; // the callback to 2s loop
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
mHandler = new Handler();
mCallback = new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(new EB_TapCard());
// schedule next run here
scheduleNextRun();
}
};
}
@Override
public void onResume() {
scheduleNextRun();
}
@Override
public void onPause() {
cleanUpRun();
}
@Override
public void onDestroy() {
// needed in case the system will force-kill your process
cleanUpRun();
}
private void cleanUpRun() {
if (mHandler != null) {
mHandler.removeCallbacks(mCallback);
}
}
private void scheduleNextRun() {
// clean up beforehand
cleanUpRun();
if (mHandler != null) {
mHandler.postDelayed(mCallback, 2000L);
}
}
想法是,每次进入页面时,您都会延迟可运行对象,并在外出时将其删除;一旦运行它并执行了回调,就可以安排下一次运行,依此类推。