Android broadcastreceiver not triggering when app is not running

后端 未结 2 1592
悲&欢浪女
悲&欢浪女 2021-01-20 02:59

Following this guide https://developer.android.com/training/monitoring-device-state/battery-monitoring.html

I made a receiver that should log battery info to a file

相关标签:
2条回答
  • 2021-01-20 03:34

    Try to set android:enabled="true" to your receiver

    Like this

     <receiver android:name=".Receiver"
        android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
            </intent-filter>
        </receiver>
    

    Update

    I just implemented it in my app your's way and it worked. But I did it with right click->new->other->broadcast receiver

    After inserting intent-filter I got code like this

        <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
            </intent-filter>
        </receiver>
    

    And it actually calling onReceive method

    0 讨论(0)
  • 2021-01-20 03:34

    Did you try using wake-locks? Generally app will wake up on the receive of broascast butif it doesnot (happens in few devices), then try using wake-locks which will forcefully wake up the device.

    How to use wake-locks :

    //Register for wake-locks

    if (mWakeLock == null) {
            PowerManager pm = (PowerManager)yourcontext.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, yourcontext);
            mWakeLock.setReferenceCounted(false);
    

    }

    //Apply wake-lock using acquire

    mWakeLock.acquire();
    
    0 讨论(0)
提交回复
热议问题