我知道这是一个热门话题,但我找不到适合我的案例。为了在我的设计中获得一些模块化,我创建了一个单一的广播接收器,可以监听任何网络状态变化,并作为(现在连接)广播到我的应用程序的通用网关。这个类叫做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";
答案 0 :(得分:0)
好的,我通过创建一个扩展BroadcastReceiver的非匿名内部类来解决这个问题。不知道为什么另一种方式不起作用。修改后的代码基本上是第二个框,现在看起来像这样:
class LocalBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"got connection info!");
}
};
就像之前一样,我在Fragment的范围内创建了这个内部类的全局实例,就像之前我在onCreate中注册它并在onDestroy中取消注册它一样。
答案 1 :(得分:0)
会:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connectivityReceiver = new ConnectivityReceiver(); // why did you do this?
Log.d(TAG,"onCreate");
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());
}
工作?