我知道这是一个热门话题,但我找不到适合我的案例。为了在我的设计中获得一些模块化,我创建了一个单一的广播接收器,它可以监听任何网络状态的变化,并作为一个通用网关(现在是连接)广播到我的应用程序中。这个类被称为 ConnectivityReceiver,它基本上是这样的:
public class ConnectivityReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectivityReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"onReceive called");
Log.d(TAG,"Intent.getAction() is "+intent.getAction());
if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
Intent out = new Intent(MapFragment.ACTION_LOCAL_CONNECTIVITY_CHANGE);
Log.d(TAG,"Sending broadcast");
context.sendBroadcast(out);
}
}
}
我确实在 Manifest 中注册了它,它运行得很好。然后,我有一个片段有兴趣了解这种连接变化,所以我创建了一个简单的内部 BroadcastReceiver,如下所示:
public BroadcastReceiver connectivityReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"got connection info!");
}
};
这个没有在 Manifest 中注册,但我确实很注意分别在片段的 onCreate 和 onDestroy 方法中注册和取消注册它。像这样的东西:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate");
connectivityReceiver = new ConnectivityReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MapFragment.ACTION_LOCAL_CONNECTIVITY_CHANGE);
this.getActivity().registerReceiver(connectivityReceiver, intentFilter);
/* Creating a ParseHandler, this will be needed for the PathParser */
mParserHandler = new ParserHandler(getActivity());
}
和
@Override
public void onDestroy(){
Log.d(TAG,"onDestroy");
this.getActivity().unregisterReceiver(connectivityReceiver);
}
但是由于某些未知原因,链中的第二个广播接收器没有收到广播!它正在发布,因为第一个(在 Manifest 中注册的)正在获取它。
有任何想法吗?自定义操作名称如下所示:
public static final String ACTION_LOCAL_CONNECTIVITY_CHANGE = "com.spiral.android.transito.CONNECTIVITY_CHANGE";