0

Disclaimer: I am an embedded SW engineer playing with Android on weekends. I come from a world where every bytes (used to) count.

I want to implement an IntentService that will process different intents. I have found different solutions but none of them seems nice to me:

1. Define an enum of actions as a resource in xml: My first idea was to create an enum in a Resource xml:

<resources>
    <declare-styleable name="MyAttrs">
        <attr name="myEnum" format="enum">
            <enum name="INTENT1" value="0"/>
            <enum name="INTENT2" value="1"/>
            <enum name="INTENT3" value="2"/>
        </attr>
    </declare-styleable>
</resources>

But the Kotlin code to use this enum is not the that easy/readable: How to get an enum which is created in attrs.xml in code

2. Define an enum of actions as an enum class:

enum class MyEnum {
    INTENT1,
    INTENT2,
    INTENT3
}

But it seems that enums are actually not very appreciated in the Android world: Should I strictly avoid using enums on Android?

3. Define constant string in my Intent Service and create an access it from the sender:

public class MyIntentService extends IntentService {
 private static final String INTENT1 = "com.myapp.intent.action.INTENT1";
 private static final String INTENT2 = "com.myapp.intent.action.INTENT2";
[...]

In the sender (in my case it's a widget):

import com.myapp.MyIntentService

class MyWidget : AppWidgetProvider() {
[...]
    private fun getPendingIntent1(context: Context, value: Int): PendingIntent {
        val intent = Intent(context, MyIntentService::class.java)
        intent.action = MyIntentService.INTENT1
        return PendingIntent.getActivity(context, value, intent, 0)
    }

Here I don't understand how defining actions as string can be better. I can't find the link again, but I read the compiler does some optimizations on its side. Is this true?

Finally, can someone tell me what is the cleanest way to define intents of IntentServices?

Thanks!

Plouff
  • 3,290
  • 2
  • 27
  • 45
  • "I want to implement an IntentService that will process different intents" -- `IntentService` has been deprecated for a few years. "But it seems that enums are actually not very appreciated in the Android world" -- they are, save for some misinformation by one particular Google developer relations engineer. "can someone tell me what is the cleanest way to define intents of IntentServices?" -- nobody is going to know what you consider to be "clean". And, since `IntentService` is deprecated, you might consider using something else, such as `WorkManager`. – CommonsWare Oct 03 '21 at 15:52
  • Besides, you can replace the intents with one intent carrying a request/command? Your IntentService can get required information to operate from this request(sealed?). How does this sound? But, as already mentioned, it is deprecated. – rupinderjeet Oct 03 '21 at 16:05
  • Ok, thanks to both of you :)! – Plouff Oct 03 '21 at 20:58

0 Answers0