我正在建立一个用于在应用中跟踪用户事件的库。当用户在应用程序的主屏幕上按两次音量按钮到我的库时,我想要回调。如何在不延长活动的情况下获得回调。 onKeyDown仅适用于活动 我试过了
public class SettingsContentObserver extends ContentObserver
{
int previousVolume;
Context context;
public SettingsContentObserver(Context c, Handler handler)
{
super(handler);
context = c;
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
previousVolume = audio.getStreamVolume(AudioManager.RINGER_MODE_NORMAL);
Log.i("myTag", "SettingsContentObserver previousVolume = " + previousVolume);
}
@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.RINGER_MODE_NORMAL);
Log.d("myTag", currentVolume + " currentVolume");
int delta = previousVolume - currentVolume;
if (delta > 0)
{
Log.i("myTag", delta + " Decreased");
previousVolume = currentVolume;
}
else if (delta < 0)
{
Log.i("myTag", delta + " Increased");
previousVolume = currentVolume;
}
}
}
当音量没有变化时,这不会调用onChange。例如,如果用户按下音量增大按钮时音量已满,则不会调用该音量。类似地,当音量为0时,如果用户按下音量,则不会调用它。如何获得回调?
答案 0 :(得分:0)
我不知道在主屏幕中如何收听关键事件,但是有一种方法可以使用内容观察器来收听音量变化。它就像一个广播接收器,当音量,联系人,通话记录等内容发生变化时被调用。但是当手机处于睡眠状态时,这将不起作用。
以下是代码:
public class Service_VolumeListener extends Service{
AudioManager audioManager;
Handler handler;
private ContentObserver volumeObserver = new ContentObserver(handler) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (audioManager != null) {
final int volume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
Log.d("VOL_STATS", "Volume Changed: " +volume);
}
}
};
@Override
public void onCreate() {
super.onCreate();
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
Uri uri = Settings.System.getUriFor(Settings.System.VOLUME_SETTINGS[AudioManager.STREAM_RING]);
getContentResolver().registerContentObserver(uri, true, volumeObserver);
//Volume listener Registered
}
@Override
public void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(volumeObserver);
//Volume service unregistered
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}