Android 手机锁定时的收听音量按钮

Android 手机锁定时的收听音量按钮,android,service,broadcastreceiver,volume,locked,Android,Service,Broadcastreceiver,Volume,Locked,我的应用程序中有一个在后端运行的服务,该服务可以在我按音量增大按钮时启动,在我按音量减小按钮时停止 public class SettingsContentObserver extends ContentObserver { int previousVolume; Context context; public SettingsContentObserver(Context c, Handler handler) { super(handler); context=c;

我的应用程序中有一个在后端运行的服务,该服务可以在我按音量增大按钮时启动,在我按音量减小按钮时停止

public class SettingsContentObserver extends ContentObserver {


int previousVolume;
Context context;

public SettingsContentObserver(Context c, Handler handler) {
    super(handler);
    context=c;

    AudioManager audio = (AudioManager)        context.getSystemService(Context.AUDIO_SERVICE);
    previousVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

}



@Override
public boolean deliverSelfNotifications() {
    return super.deliverSelfNotifications();
}

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);

    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

    int delta=previousVolume-currentVolume;



        if(delta > 0)
        {
            System.out.println("Decreased") ;
            Intent intent = new Intent(context, MyAlarmService.class);
            context.stopService(intent);
            previousVolume=currentVolume;
        }
        else if(delta < 0)
        {
              System.out.println("Increased");
              Intent intent = new Intent(context, MyAlarmService.class);
              context.startService(intent);
              previousVolume=currentVolume;
        }


}
}
在android清单中,我添加:

<receiver android:name="YourBoardcastReceiver">
            <intent-filter>
                    <action android:name="android.intent.action.SCREEN_ON" />
            </intent-filter>
    </receiver>
请问我能给我一些帮助吗,
思考。

尝试向广播接收器注册Intent.ACTION\u SCREEN\u OFF和Intent.ACTION\u SCREEN\u ON

当手机处于锁定/睡眠模式时,我们无法收听按钮的变化,但我们可以做一些调整来收听音量按钮

Github:

这些应用程序正在后台播放0卷的媒体,然后使用MediaButtonInt的接收者将始终收听该键

<receiver android:name="YourBoardcastReceiver">
            <intent-filter>
                    <action android:name="android.intent.action.SCREEN_ON" />
            </intent-filter>
    </receiver>
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName mRemoteControlResponder = new ComponentName(getPackageName(),
YourBoardcastReceiver.class.getName());