我在後臺運行的應用程序中有一項服務,當按按鈕音量時可以啓動服務,按下按鈕音量時可停止服務。手機鎖定時收聽音量按鈕android
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.STREAM_RING);
}
@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_RING);
int delta=previousVolume-currentVolume;
if(delta > 0)
{
System.out.println("Decreased") ;
Intent intent = new Intent(context, MyAlarmService.class);
context.stopService(intent);
previousVolume=currentVolume;
}
else if(delta < 0)
{
System.out.println("Increased");
Intent intent = new Intent(context, MyAlarmService.class);
context.startService(intent);
previousVolume=currentVolume;
}
}
}
我想要做同樣的事情時,我的手機被鎖定(當屏幕關閉),當我在網上搜索我發現我必須使用BroadcastReceivre,我測試,但它不工作。
public class YourBoardcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("get something", "i dont know what!!");
String intentAction = intent.getAction();
KeyEvent event = null;
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
event = (KeyEvent) intent
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
}
if (event == null) {
return;
}
int keycode = event.getKeyCode();
int action = event.getAction();
long eventtime = event.getEventTime();
if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
if (action == KeyEvent.ACTION_DOWN) {
Intent intent1 = new Intent(context, MyAlarmService.class);
context.stopService(intent1);
if (isOrderedBroadcast()) {
abortBroadcast();
}
else if (action == KeyEvent.ACTION_UP) {
Intent intent11 = new Intent(context, MyAlarmService.class);
context.startService(intent11);
}
if (isOrderedBroadcast()) {
abortBroadcast();
}
}
}
}
}
在Android清單我補充一下:
<receiver android:name="YourBoardcastReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
還有在梅索德在MainActivity oncrete我補充一下:
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName mRemoteControlResponder = new ComponentName(getPackageName(),
YourBoardcastReceiver.class.getName());
普萊斯我能不能給我一些幫助, 思。