In my android application I am firing predefined notifications at predefined times daily which seeks user's input. I am using powerManager
class class & acquiring wake lock. I am able to do that but my requirement is that my notification should wait if the user is actively doing something with his/her device.
I have tried this by using isInteractive()
method (code below) provided by the powerManager
class and the OS sometimes throws ANR (Application not responding) and it sometimes skips the notification altogether.
I have created a new thread simply to make my app wait until the device is not being used and then I have called my notification firing section.
Public class myClass extends BroadcastReceiver{
private void checkPhoneUsage(Context context, int alarmId){
final PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mThread = new Thread(new Runnable() {
@Override
public void run() {
try{
if(Build.VERSION.SDK_INT >= 20)
while(pm.isInteractive())
Thread.sleep(10000);
else if (Build.VERSION.SDK_INT < 20)
while (pm.isScreenOn())
Thread.sleep(10000);
// Call the method which fires Notification.
// fireNotification(alarmId);
}
catch (Exception e){
Log.e(Tag,"Error during thread.sleep");
}
}
});
}
}
I tried using SystemClock.wait(ms)
but again the problem repeats, also this fails because it should not be used on a UI Thread.
You shouldn't. Look at the documentation for isInteractive:
The system will send a screen on or screen off broadcast whenever the interactive state of the device changes. For historical reasons, the names of these broadcasts refer to the power state of the screen but they are actually sent in response to changes in the overall interactive state of the device, as described by this method.
Instead, use a broadcast for screen off. Then do whatever code you want in that receiver. Or if you need it to happen on the other thread, have that thread wait for a message sent from this receiver.