Android:在库中注册接收器

Ogu*_*han 5 android broadcastreceiver android-context

我有一个库,其中包含一个名为 as 的活动BaseActivity和一个名为 as 的接收器BaseRegister

BaseRegisterextendsBroadcastReceiver和它的动作是android.net.conn.CONNECTIVITY_CHANGEandroid.net.wifi.WIFI_STATE_CHANGED,它看起来像:

public class BaseRegister extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if {
            Log.d("onReceive", "Got it"); // Works
            context.sendBroadcast(new Intent("some"));
        else {
            Log.d("onReceive", "Nope"); // Works
            context.sendBroadcast(new Intent("stuff"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

AndroidManifest根据Log. 下面是它的BaseActivity样子:

public class BaseActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(applicationControl, new IntentFilter("some"));
        registerReceiver(applicationControl, new IntentFilter("stuff"));
    }

    private BroadcastReceiver applicationControl = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.equals(new Intent("some"))) {
                some();
            } else if (intent.equals(new Intent("stuff"))) {
                stuff();
            }
        }
    };

    public void some() { /** logging etc **/ }
    public void stuff() { /** logging etc **/ }


}
Run Code Online (Sandbox Code Playgroud)

在项目中,我已经将此项目添加为库,没问题。并创建了一个扩展BaseActivity. 当CONNECTIVITY_CHANGE作为一个动作时,BaseRegister由 Android 触发,但没有调用 Activity。这是我的项目的外观:

public class AnyActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
}

    @Override
    public void some() {
        super.some();
        Log.d("abc", "abc"); // not working
    }


    @Override
    public void stuff() {
        super.stuff(); 
        Log.d("abc", "abc"); //not working
    }

}
Run Code Online (Sandbox Code Playgroud)

怎么了?我的方法是否不当或是否存在任何错误?任何帮助都会很棒。

小智 1

BaseActivity 将调用范围内“最接近”的方法,这是正常的核心 Java 行为,并非 Android 所独有。如果您确实想将 BroadcastReceiver 保留在基类中并向子级发送信号,那么您将需要诸如自定义侦听器之类的东西,即子级在运行时注册,并且当事件到达时它们将收到通知。

此外,当 Activity 不在堆栈顶部时禁用广播接收器被认为是一种很好的做法,因此您可能希望在 onResume()/onPause() 中使用 registerReceiver()/unregisterReceiver()

祝你好运。