简体   繁体   中英

ACTION_SCREEN_OFF background service trigger

I have a notification being fired through AlarmManager and the notification also plays a sound.

Obviously, it may happen that the alarm is fired when the app is in the background, and I would like to let the user cancel the sound when pressing the lock button - ie listening for ACTION_SCREEN_OFF .

Therefore I wonder if it's possible to start a service and listen for ACTION_SCREEN_OFF ?

I have seen Listening for ACTION_SCREEN_OFF but that solution of having a BroadCastReceiver only seems to work when the app is in the foreground. Right?

For instance if you are trying to do ACTION_SCREEN_OFF then you would define your broadcast receiver in your Activity that started the alarm for instance.

public class SomeListener extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
      //Turn off sounds
    }
}

Then in the manifest provide something of the sort like this within the activity that uses the listener.

<intent-filter>
    <action  android:name="android.hardware.usb.action.ACTION_SCREEN_OFF" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.ACTION_SCREEN_OFF"
                         android:resource="@xml/my_filter" />

Where the extra my_filter class could provide additional meta-data. In this case it was a check against a Serial or UUID of the device so not to launch on all USB connects. But you should be able to do something similar.

When the action occurs, this should fire the listener within your application, as I understand it anyways. This feature works for launch of application on USB connect for me in the past. Even without having had the application open in the first place.

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