Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/223.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android后台广播接收器,但动态创建_Android_Android Broadcastreceiver - Fatal编程技术网

Android后台广播接收器,但动态创建

Android后台广播接收器,但动态创建,android,android-broadcastreceiver,Android,Android Broadcastreceiver,我目前正在尝试让广播接收器在我的android应用程序的后台运行,我被告知要为它使用事件服务。目前,我的广播接收器工作良好,如果你在他们注册的活动 private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent intent) { if(intent.getAction().equal

我目前正在尝试让广播接收器在我的android应用程序的后台运行,我被告知要为它使用事件服务。目前,我的广播接收器工作良好,如果你在他们注册的活动

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {
            Toast.makeText(arg0, "Battery's dying!!", Toast.LENGTH_LONG).show();
            Log.e("LOW", "LOW");
            intent = null;
        }else if(intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
            Toast.makeText(arg0, "Battery's discharging!!", Toast.LENGTH_LONG).show();
            Log.e("discharge", "discharge");
            intent = null;
        }else if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
            Toast.makeText(arg0, "Battery's charging!!", Toast.LENGTH_LONG).show();
            Log.e("charge", "charge");
            intent = null;
        }else if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY)) {
            Toast.makeText(arg0, "Battery's okay!!", Toast.LENGTH_LONG).show();
            Log.e("OKAY", "OKAY");
            intent = null;
        }
    }
};
在OnCreate中:

    registerReceiver(this.mBatInfoReceiver,
            new IntentFilter(Intent.ACTION_BATTERY_LOW));
    registerReceiver(this.mBatInfoReceiver,
            new IntentFilter(Intent.ACTION_BATTERY_OKAY));
    registerReceiver(this.mBatInfoReceiver,
            new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
    registerReceiver(this.mBatInfoReceiver,
            new IntentFilter(Intent.ACTION_POWER_CONNECTED));
尽管在oncreate中使用IntentFilter会出现泄漏问题,但我当前的问题是,当我更改活动时,这些过滤器将不再运行,我已阅读了以下内容:

通过将它们放入IntentService并启动此服务,它们将一致运行,但这涉及在清单中注册接收者,这给了我一个问题,因为我的应用程序计划允许用户监听特定事件,即:这些事件无法动态创建


是否有一种方法可以在类中动态创建广播接收器,该类在应用程序的后台运行,并在广播发生时触发?

您是否尝试将它们封装在将在每个“活动”中设置的单例类中?你在使用DI吗?但是当应用程序关闭时,接收器会关闭?啊,当应用程序关闭时,会错过持久化。实现这一点的唯一方法是使用在后台运行的服务。(我目前正在做类似的事情)。一个倾听者可能会很好地满足你的需要——在其中一个回答中有一个例子似乎是你想要完成的。