Search code examples
androidandroid-intentbroadcastreceiverandroid-broadcast

Android: How to use switch-case with intents received from Broadcasts


I want to analyse an intent receiving from a broadcast. Because there could be different intents from different broadcasts. To evaluate the different broadcasts I want to use a switch case statement like this:

public void onReceive(Context context, Intent intent) {
    switch (intent.getAction()) {
    case Intent.ACTION_SCREEN_OFF:
        //code for this intent
    }
}

But I know it is not possible to create a switch case statement like this, so I think I need something like an integer value to identify the intents, but I can't find a method to get such a value from my intent.

Can anybody tell me how to analyse the different intents with a switch case statement?

Edit: Works with else-if, but I want to use switch-case


Solution

  • All Intent.ACTION_* fields are String constant.

    You cannot use switch with String until JDK 7 android use JDK 6 or 5 to compile. So you can't use that method on Android

    But you can use else if

    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) {
        // Do
    } else if (intent.getAction().equals(Intent.ANYTINGS) {
        //do
    }
    

    Official documentation