简体   繁体   中英

onReceive() is not always called

For some reason, the onReceive() method of my BroadcastReceiver class is not always called. It is usually called, but sometimes it is not.

More specifically, I am receiving android.intent.action.PHONE_STATE . Most of the time, when a call comes in, the onRecieve() method is called as it should be for changes to RINGING, IDLE, and OFFHOOK. However, there are some occasion when the method is NOT called for RINGING (when a call is incoming) but it is still called for IDLE (when I hang up the call).

From the manifest:

    <receiver android:name=".CallReceiver">
        <intent-filter android:priority="999">
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

The onReceive method itself is pretty simple:

public void onReceive(Context voCtx, Intent voIntent)
{
    Log(voCtx, "onReceive: " + voIntent.getAction());
    if(voIntent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED))
    {
        HandleCallStateChanged(voCtx, voIntent);
    }
}

Log just outputs to my log file, so I can see what's happening. I'm not sure why onReceive() is only called sometimes. Could some other app be intercepting the broadcasts and cancelling them before my app gets them?

Android now has a feature of Doze and App standby. So, if your app enters this mode, then your BroadcastReceiver will not trigger.

To allow your receiver to get triggered you can make use of REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission . This way your app will be excluded from the battery optimisation process.

CAUTION: GOOGLE MAY BAN YOUR APP IF YOU DON'T USE THIS PERMISSION WITH CARE

It looks like this is specific to Samsung phones. Under the battery settings, there is an "App power monitor" (in addition to the normal Battery Optimization stuff). This App power monitor can put apps to "sleep" (which is different from App Standby). Setting my app as an "Unmonitored app" seems to have fixed my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM