我有一个处理程序,我发送到Intent服务以便稍后接收消息并通知UI。我遇到的问题是,我很快失去了弱引用,而且我无法通知活动我收到了Intent服务请求的信息。
这是我的班级,持有信使:
public class UserManager extends Observable {
MessengerHandler handler = new MessengerHandler(this);
UserManager(Activity activity) {
mActivity = activity;
}
@Override
public void find() {
Messenger messenger = new Messenger(handler);
Intent intent = new Intent(mActivity, UserIntentService.class);
intent.putExtra(MESSENGER_KEY, messenger);
mActivity.startService(intent);
}
static class MessengerHandler extends Handler {
private final WeakReference<UserManager> outerClass;
public MessengerHandler(UserManager outer) {
outerClass = new WeakReference<UserManager>(outer);
}
@Override
public void handleMessage(Message msg) {
if (outerClass.get() == null) {
Log.e(LOG_TAG, "Weak reference lost, impossible to notify UI");
return;
}
outerClass.get().setChanged();
outerClass.get().notifyObservers();
}
}
}
和onHandle意图:
protected void onHandleIntent(Intent intent) {
Message msg = Message.obtain();
Bundle data = new Bundle();
data.putInt(CloudManager.REQUEST_CODE_KEY, intent.getIntExtra(CloudManager.REQUEST_CODE_KEY, 0));
msg.setData(data);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}