Android后台BroadcastReceivers但动态创建

时间:2016-03-08 13:05:27

标签: android android-broadcastreceiver

我目前正试图在我的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时泄漏了intentfilters会出现问题,但我当前的问题是当我更改活动时这些问题不再运行时,我已经从以下内容中读到:http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#startingservices_alarmmanager

通过将这些放入IntentService并启动此服务,它们将一致地运行,但这涉及在清单中注册接收器,这给我带来了问题,我的应用程序正在计划允许用户监听特定的事件IE:这些不能动态创建。

有没有办法在类中动态创建广播接收器,该广播接收器在应用程序的后台运行并在广播发生时触发?

0 个答案:

没有答案