Search code examples
androidnotificationsled

how to cancel led notification , when screen is unlocked in android?


i have an app that when airplane mode is on , led light notification start . i want to stop or cancel this led light , when my screen is unlocked.how can i handle this?

i try this but not worked:

....
 PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();
    if (isScreenOn) {
        stop();
    }
}


public void stop(){
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(NOTIFICATION_ID);
        }


}

if i want to cancel this led light , when airplane mode is off, how can i check this event?

thanks...


Solution

  • Firstly, handle the (ACTION_USER_PRESENT) http://developer.android.com/reference/android/content/Intent.html#ACTION_USER_PRESENT -- this is when the device is unlocked. Then do the cancellation.

    <receiver android:name=".Receive">
        <intent-filter android:enabled="true" android:exported="false">
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
    
    public class Receive extends BroadcastReceiver {
        if (intent.getAction() != null) {
            if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                if (Context.NOTIFICATION_SERVICE != null) {
                    String ns = Context.NOTIFICATION_SERVICE;
                    NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
                    nMgr.cancel(0);
                }
            }
        }
    }
    

    I have not tested this code, so you may need to modify it. But hopefully the concept is right.