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 s
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