BroadcastReceiver not working after BOOT_COMPLETED

后端 未结 1 1533
轮回少年
轮回少年 2021-01-11 10:51

I\'m trying to intercept incoming SMS right after boot_completed but i\'m having a problem with a NullPointerException in this line:

Object[] rawMsgs=(Object         


        
相关标签:
1条回答
  • 2021-01-11 11:02

    The problem here is that your BroadcastReceiver implementation has been mapped to two intents - android.provider.Telephony.SMS_RECEIVED and android.intent.action.BOOT_COMPLETED - but in the onReceive implementation you're not checking which intent you are processing.

    My guess is that android.intent.action.BOOT_COMPLETED has been received and intent.getExtras() is returning null. You could confirm this by adding some logging to the method and watching the logcat window (if you're using Eclipse).

    If you write a service or broadcast receiver and map it to multiple intents it is good practice - nay essential - to check which intent has been received and process it appropriately. Personally I'd go for something like this:

    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        // boot-related processing here
    }
    else if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        // SMS-related processing here
    }
    else {
        // intent not handled - log as a warning as you've registered to receive it
    }
    

    You can't assume fail-safe behaviour. For clarity, move the intent processing logic into a separate method:

    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        processBootCompletedIntent(intent);
    }
    else if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
        processSmsReceivedIntent(intent);
    }
    else {
        // intent not handled - log as a warning as you've registered to receive it
    }
    

    PS - most (if not all) 'native' intent action strings are held as constants in a relevant class. For example android.intent.action.BOOT_COMPLETED is defined as Intent.ACTION_BOOT_COMPLETED. Use the constants where they exist, it'll save you making any typing errors.

    0 讨论(0)
提交回复
热议问题