我在下面的代码下面将在我完成活动时从另一个线程中执行回调。那么如何避免在活动完成后调用回调或回调中的代码?
public static interface Callback{
public void onCallback();
}
class ActivityA {
TextView tv = ...;
Handler handler = ...;
public void onClick(View v) {
Business.callThread(new Callback() {
@Override
public void onCallback() {
handler.post(new Runnable(){
public void run(){
tv.setText("xxxx");
}
});
}
});
}
}
class Business {
public static void callThread(final Callback listener) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000); //sleep 5s;
} catch (InterruptedException e) {
e.printStackTrace();
}
listener.onCallback();
}
}).start();
}
}
垃圾收集器计数对象的引用。但是,有几种参考类型。在您的情况下有用是WeakReference
:
弱参考对象,不会阻止其参考者被最终确定,然后进行回收。
使用构造函数创建可运行的类:
static class CallbackRunnable implements Runnable {
WeakReference<Callback> listener;
public CallbackRunnable(Callback listener) {
this.listener = new WeakReference<Callback>(listener);
}
@Override
public void run() {
try {
Thread.sleep(5000); //sleep 5s;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (listener.get() == null) {
return;
}
listener.get().onCallback();
}
}
然后称呼听众:
if (listener.get() == null) {
return;
}
listener.get().onCallback();
callThread
方法实现:
public static void callThread(final Callback listener) {
new Thread(new CallbackRunnable(listener)).start();
}