Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any way to detect volume key presses or volume changes with android service?

Some Android apps generate a notification when the device's volume changes and some lock the volume. For the life of me, I cannot find out how that's done. Please, can someone help me by providing an example?

like image 957
kevdliu Avatar asked Dec 27 '22 14:12

kevdliu


1 Answers

Actually there is one way you can do in service by using Content Observer. It works like a broadcast receiver, listen to the event of changing content such as volume, contacts, call log...

Using the following code in your service

public class VolumeService extends Service{ 
AudioManager mAudioManager;
Handler mHandler;

private ContentObserver mVolumeObserver = new ContentObserver(mHandler) {
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        if (mAudioManager != null) {

            final int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
            System.out.println("Volume thay đổi: " +volume);

            Intent photoIntent = new Intent(VolumeService.this,TakePhotoActivity.class);
            photoIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(photoIntent);
        }
    }
};





@Override
public void onCreate() {
    super.onCreate();

    System.out.println("Volume Service started");

    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    Uri uri = Settings.System.getUriFor(Settings.System.VOLUME_SETTINGS[AudioManager.STREAM_RING]);
    getContentResolver().registerContentObserver(uri, true, mVolumeObserver);

    System.out.println("Đã đăng ký Volume listener");
}



@Override
public void onDestroy() {
    super.onDestroy();      
    System.out.println("Volume service destroied");

    getContentResolver().unregisterContentObserver(mVolumeObserver);
}



@Override
public IBinder onBind(Intent arg0) {

    return null;
}

}

Don't forget to declare it in the Android Manifest.xml

<service android:name=".service.VolumeService" >
like image 173
mvmanh Avatar answered Jan 03 '23 00:01

mvmanh