问题描述
我正在 Android 中实现 REST 客户端.我看过一个例子,它使用 Service
来执行与服务器的连接,并使用 ResultReceiver
来通知操作完成.我正在从片段调用服务,如果我尝试在服务运行时旋转屏幕,ResultReceiver
中的 getActivity() 方法将返回 null,因为该片段可能不再处于布局中.
I am implementing a REST client in Android.
I have seen an example of using a Service
to perform the connection to the server and the ResultReceiver
to be notified of the operation completion. I am calling the service from a fragment and, if I try to rotate the screen while the service is running, the getActivity() method in ResultReceiver
returns null because probably that fragment is not in layout anymore.
片段中的回调方法:
@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.这是正常的吗?即使在屏幕旋转时,我也可以使用什么方法来允许通知?本地广播?
The getActivity()
returns null.
Is this normal? What approach could I use to allow notification even on screen rotation? Local Broadcast?
推荐答案
我正在使用使用 LocalBroadcastManager
注册的 BroadcastReceiver
并且它工作正常.事情没那么简单.是否存在更好的解决方案?
I am using a BroadcastReceiver
registered using LocalBroadcastManager
and it is working properly. It wasn't so simple. Does a better solution exist?
这篇关于ResultReceiver 不支持屏幕旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论