2014年9月27日 星期六

[android] service 處理音量鍵

android service 收不到key event.
可以透過 AUDIO_SERVICE

    
public class SettingsContentObserver extends ContentObserver {
        int previousVolume;
        Context context;

        public SettingsContentObserver(Context c, Handler handler) {
            super(handler);
            Log.d(TAG,"SettingsContentObserver()");
            context=c;

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

        @Override
        public boolean deliverSelfNotifications() {
            Log.d(TAG,"deliverSelfNotifications()");
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            Log.d(TAG,"onChange()");
            super.onChange(selfChange);

            AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            int currentVolume = audio.getStreamVolume(AudioManager.STREAM_SYSTEM);            
            Log.d(TAG,"onChange() currentVolume = "+currentVolume);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate()");
        mSettingsContentObserver = new SettingsContentObserver(this,new Handler());
        getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver );        
    }
    @Override
    public void onDestroy() {
        Log.d(TAG,"onDestroy()");
        getContentResolver().unregisterContentObserver(mSettingsContentObserver);
    }

沒有留言:

張貼留言