我正在尝试从静态广播接收器更新我的活动中的片段 - 但它不起作用
public static class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, new Fragment1());
fragmentTransaction.commit();
}
}
getFragmentManager()存在问题:
无法从类型Activity
中对非静态方法getFragmentManager()进行静态引用答案 0 :(得分:1)
您可以从类定义中删除static修饰符。
public class NetworkChangeReceiver extends BroadcastReceiver {
这样您就可以访问外部环境,如果它是Activity
的实例,则可以访问getFragmentManager
/ getSupportFragmentManager
。
编辑:
以编程方式注册BroadCast接收器
声明为成员变量
NetworkChangeReceiver mNetworkChangeReceiver;
的onCreate:
mNetworkChangeReceiver = new NetworkChangeReceiver()
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(mNetworkChangeReceiver, intentFilter);
和onDestroy取消注册:
unregisterReceiver(mNetworkChangeReceiver);