0

我知道这是一个热门话题,但我找不到适合我的案例。为了在我的设计中获得一些模块化,我创建了一个单一的广播接收器,它可以监听任何网络状态的变化,并作为一个通用网关(现在是连接)广播到我的应用程序中。这个类被称为 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";
4

2 回答 2

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());
}

工作 ?

于 2013-04-27T16:07:21.047 回答
0

好的,我通过创建一个扩展 BroadcastReceiver 的非匿名内部类来解决这个问题。不知道为什么其他方式不起作用。被修改的代码基本上是第二个框,现在看起来像这样:

class LocalBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"got connection info!");
    }
};

就像以前一样,我在 Fragment 的范围内创建了这个内部类的全局实例,就像在 onCreate 中注册它并在 onDestroy 中取消注册它一样。

于 2012-04-14T20:35:35.300 回答