BroadcastReceiver not working after BOOT_COMPLETED

百般思念 提交于 2019-12-01 02:51:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!