Is it possible to define a broadcast receiver as a

2019-01-07 14:37发布

This question already has an answer here:

I want to create a broadcast receiver as an inner class in my main activity. But I have problems defining the broadcast receiver in manifest xml file, because android can't find it.

Code:

public class MyActivity extends Activity{
    ...

    public class Receiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ....
        }

    }

    ...
}

Manifest:

<receiver android:name=".org.danizmax.myapp.MyActivity$Receiver" android:enabled="true">
            <intent-filter>
                <action android:name="org.danizmax.myapp.BROADCAST_INITIAL_DATA"></action>
            </intent-filter>
</receiver>

I tried with:

  • .org.danizmax.myapp.MyActivity$Receiver
  • org.danizmax.myapp.MyActivity$Receiver
  • .MyActivity$Receiver
  • .Receiver

I saw others also having similar problems, but did not find any answers.

So is it possible? If not, what's better way to use broadcast receivers?

Thanks!

3条回答
何必那么认真
2楼-- · 2019-01-07 14:51

Yes, it is possible.

The receiver android:name attribute should look like .path.to.class.MyClass$MyInnerClass

查看更多
三岁会撩人
3楼-- · 2019-01-07 14:52

The better way to use BroadcastReceivers would be to make it its own class. That way the code is better organized and you can possible reuse it.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-07 15:01

If you want to this with a non-static inner class, you can't do it via the AndroidManifest.xml. You can however dynamically register the BroadcastReceiver: Receiver as inner class in Android

查看更多
登录 后发表回答