【发布时间】:2016-12-03 21:18:15
【问题描述】:
我有一个 Main Activity,它包含 1 个片段。该片段负责绘制 UI、运行异步任务等。所有这些都需要互联网连接。现在,当我第一次启动我的应用程序时,我会通过一种方法检查是否有互联网连接:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());
}
如果没有网络连接,则 Activity 会启动片段,但我已经做到了,因此在没有 Internet 连接的情况下什么都不会显示(因为我正在从在线数据库下载内容,所以什么都不会显示)。
我想实现一个广播接收器,当有可用的互联网连接时,它会以某种方式重新启动片段。到目前为止,我的主要活动中有一个广播接收器作为内部类:
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Toast.makeText(context, "internet ++", Toast.LENGTH_LONG).show();
//this is where the fragment needs to be somehow reinstantiated
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "internet --", Toast.LENGTH_LONG).show();
}
}
}
};
我试图让广播接收器成为一个外部类,但是我无法对片段做任何事情。当它是一个内部类时,广播接收器的代码不会发生任何事情。我已经查看了很多类似的问题,但似乎没有什么对我有用。
所以手头的问题是:当应用运行时互联网连接可用时,如何刷新 Activity 中的片段?
【问题讨论】:
-
如果 Fragment 附加到 Hosting Activity,您不需要广播接收器,您可以通过 FragmentManager (v4 - getSupportFragmentManager) 获取您的 Fragment,只需调用一个方法通过强制转换来重绘 UI你的片段类型。即
((MyFragment)getSupportFragmentManager.getFragmentByTag(fragmentTag)).updateUI();- 语法可能略有错误.. 不在电脑前。 -
@sup4eli 谢谢,我会想办法解决的..
标签: java android broadcastreceiver fragment