我正在 Android 中实现 REST 客户端。
我看过一个例子,使用 Service
执行与服务器的连接,并使用 ResultReceiver
来通知操作完成。我正在从 fragment 调用服务,如果我尝试在服务运行时旋转屏幕,ResultReceiver
中的 getActivity() 方法将返回 null,因为该 fragment 可能不再处于布局中。
fragment 中的回调方法:
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
Response response = (Response) resultData
.getSerializable(RestService.RESULT);
if (resultCode == RestService.SUCCESS
&& response != null) {
if (getActivity() != null) {
recommendationResponse = response;
getLoaderManager().restartLoader(0, new Bundle(),
Fragment.this);
}
}
}
getActivity()
返回 null。这是正常的吗?即使在屏幕旋转时,我也可以使用什么方法来允许通知?本地广播?
最佳答案
不,
android:configChanges="orientation"
不是解决方案。
要使用 ResultReceiver I:
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(Consts.RECEIVER, mReceiver);
super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mReceiver = savedInstanceState.getParcelable(Consts.RECEIVER);
}
else {
mReceiver = new MyResultReceiver(new Handler());
}
mReceiver.setReceiver(this);
}
这是我的 ResultReceiver 类:
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
public class MyResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int command, Bundle resultData);
}
@Override
protected void onReceiveResult(int command, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(command, resultData);
}
}
}