问题
I am trying to get HARDWARE_HOOK button and volume change button in my service using MediaSession for Android 5.0+ . This has to work specially when screen is off/locked. The problem is that though I am able to receive HARDWARE_HOOK button event, the volume change is not detected. the onAdjustVolume method never gets called.
import android.app.Service;
import android.content.Intent;
import android.media.MediaRouter;
import android.media.session.MediaSession;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.media.VolumeProviderCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class HookButtonService extends Service{
public static final String SESSION_TAG = "SampleApp";
private MediaSessionCompat mMediaSession;
private VolumeProviderCompat myVolumeProvider;
public class ServiceBinder extends Binder {
public HookButtonService getService() {
return HookButtonService.this;
}
}
private Binder mBinder = new ServiceBinder();
private MediaSessionCompat.Callback mMediaSessionCallback = new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("SampleApp","Media button received");
if(!MyApplication.isActivityVisible()) {
Intent dialogIntent = new Intent(getApplicationContext(), MainActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
return true;
}
};
public HookButtonService() {
}
public MediaSessionCompat.Token getMediaSessionToken() {
return mMediaSession.getSessionToken();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
mMediaSession = new MediaSessionCompat(this, SESSION_TAG);
mMediaSession.setCallback(mMediaSessionCallback);
myVolumeProvider = new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_RELATIVE, 100, 50) {
@Override
public void onAdjustVolume(int direction) {
Log.d("SampleApp","Volume change received: "+direction);
}
};
mMediaSession.setActive(true);
mMediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
mMediaSession.setPlaybackToRemote(myVolumeProvider);
}
@Override
public void onDestroy() {
super.onDestroy();
mMediaSession.release();
}
}
来源:https://stackoverflow.com/questions/44070501/onadjustvolume-not-called