我的Android应用程序必须与服务器通信。因此,活动会创建一个intent并启动一个IntentService派生。
遵循一些提示,例如this one,我扩展了ResultReceiver来处理答案: 我的活动实现了包含的Receiver接口(因此实现了onReceiveResult)。
public class MyResultDistributor extends ResultReceiver {
// Class instances serves one purpose: To remember who gets the answer.
private Receiver mReceiver;
// Constructor: Apparently, the "handler" determines in which thread the result handling is done.
public MytResultDistributor(Handler handler) {
super(handler);
}
// This is what the receiver of request answers has to implement.
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
// Allows to clarify who is the receiver of request results.
public void setReceiver(Receiver receiver) {
if (receiver != null) {
Log.d(this.getClass().toString(), "Setting receiver.");
} else {
Log.d(this.getClass().toString(), "Unsetting receiver.");
}
this.mReceiver = receiver;
if (this.mReceiver != null) {
Log.d(this.getClass().toString(), "Set receiver.");
} else {
Log.d(this.getClass().toString(), "Unset receiver.");
}
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Anybody interested in the results? Well, then feel free to take them.
Log.d(this.getClass().toString(), "Got result.");
if (this.mReceiver != null) {
Log.d(this.getClass().toString(), "Distributing result.");
this.mReceiver.onReceiveResult(resultCode, resultData);
} else {
Log.d(this.getClass().toString(), "No receiver there.");
}
}
活动创建一个这样的实例,并将自己设置为Receiver(摘录):
public class MainActivity extends Activity implements MyResultDistributor.Receiver {
public MyResultDistributor mDistributor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(this.getClass().toString(), "onCreate");
setContentView(R.layout.activity_main);
mDistributor = new MyResultDistributor(new Handler());
mDistributor.setReceiver(this);
(...)
}
@Override
protected void onPause() {
super.onPause();
Log.v(this.getClass().toString(), "onPause");
mDistributor.setReceiver(null);
}
@Override
protected void onResume() {
super.onResume();
Log.v(this.getClass().toString(), "onResume");
mDistributor.setReceiver(this);
}
(...)
现在,当我运行活动时,启动我的服务,并返回结果,似乎mReceiver
为空。但是我无法在日志中看到它被设置为null的位置!??
日志摘录:
onCreate
Setting receiver.
Set receiver.
onResume
Setting receiver.
Set receiver.
Request Service was created.
Request Service has got an Intent.
Server answer: auth
Authenticated!
Got result.
No receiver there.
其中最后5条消息具有不同的TID。
为什么接收器出现在一个方法中而在另一个方法中未设置?我有线程问题吗?使用new Handler()
可能做错了吗?
感谢您的任何提示!
答案 0 :(得分:1)
好吧我觉得我发现了自己的错误: 我以某种方式将错误的接收器传递给我的IntentService - 所以我正在观看的实例是另一个。 很抱歉这个无法解决的问题...(因为没有显示该代码部分。)。