当前位置: 动力学知识库 > 问答 > 编程问答 >

Processing MEDIA BUTTONS on android

问题描述:

I am trying to process media button presses in my application but nothing I try seems to work. Here is my broadcast receiver:

private final BroadcastReceiver receiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equalsIgnoreCase("android.intent.action.MEDIA_BUTTON")) {

Log.d("EVENT", "Media button pressed");

startStop();

}

}

};

I registerd it in the onCreate method:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

am.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));

}

I also tried other ways of doing it, like creating a separate BroadcastReceiver class and registering it via AndroidManifest...

EDIT: I went back to "separate class for receiver" way of doing it and now the damn thing works too well... let me explain; here is my brand new BroadcastReceiver class:

public class RemoteControlReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {

KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

Log.d("EVENT", "Key code: "+event.getKeyCode());

if ((KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) && (event.getAction() == KeyEvent.ACTION_DOWN)) {

Log.d("EVENT", "Received media button press");

if (MainActivity.timer.getStarted())

MainActivity.timer.stopTimer();

else

MainActivity.timer.startTimer();

}

}

}

}

registerd it in manifest with this:

<receiver android:name=".RemoteControlReceiver">

<intent-filter>

<action android:name="android.intent.action.MEDIA_BUTTON" />

</intent-filter>

</receiver>

and this comes out in log:

11-23 01:47:02.848 16956-16956/com.example.andrej.ssvcounter D/EVENT: Key code: 79

11-23 01:47:02.848 16956-16956/com.example.andrej.ssvcounter D/EVENT: Received media button press

11-23 01:47:02.873 16956-16956/com.example.andrej.ssvcounter D/EVENT: Key code: 79

11-23 01:47:04.931 16956-16956/com.example.andrej.ssvcounter D/AndroidRuntime: Shutting down VM

and then the whole thing crashes. For some reason two intents get sent and i tried to filter one out with ACTION_DOWN condition but it did not help...

分享给朋友:
您可能感兴趣的文章:
随机阅读: