I am working on an app that is going to trigger an alarm when volume key is pressed and hold for some time. I have research and it seems like some people claim it is impossible to get input feedback from a service, while others claim it is possible with an extended class of ContentObserver or using the music media api, however I still haven't been able to get it to work.
The following app does exactly what I need, when you activate it, it will take a screen shot when you press and hold the volume and power buttons after a certain period of time regardless of whether is closed, locked, etc..
https://play.google.com/store/apps/details?id=com.enlightment.screenshot&hl=en
My question is how can I do the above with a service class.
Code:
This is my ContentObserver class:
int previousVolume;
Context context;
public ContentListener(Context c, Handler handler) {
super(handler);
context=c;
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
previousVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
}
@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_MUSIC);
int delta=previousVolume-currentVolume;
if(delta>0)
{
Logger.log(Logger.LOG, "Volume Down");
previousVolume=currentVolume;
}
else if(delta<0)
{
Logger.log(Logger.LOG, "Volume Up");
previousVolume=currentVolume;
}
}
This is my Service class:
private ContentListener listener;
@Override
public void onCreate() {
Logger.log(Logger.LOG, "OnCreate");
listener = new ContentListener(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(
android.provider.Settings.System.CONTENT_URI, true, listener);
}
@Override
public void onDestroy() {
Logger.log(Logger.LOG, "OnDestroy");
getApplicationContext().getContentResolver().unregisterContentObserver(listener);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { return Service.START_STICKY; }
@Override
public IBinder onBind(Intent intent) { return null; }