我正在尝试检测Headset按钮点击这个
http://android.amberfog.com/?p=415
这是我尝试的代码
public class MainActivity extends Activity {
private IntentFilter mIntentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actvity_main);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
mIntentFilter.setPriority(2147483647);
registerReceiver(mReceiver, mIntentFilter);
}
@Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
Toast.makeText(MainActivity.this,"Your Message", Toast.LENGTH_LONG).show();
}
abortBroadcast();
}
};
@Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
我想要做的就是收到按钮点击的祝酒消息,但是没有被检测到究竟应该做什么来检测按钮点击。
我在使用Android 4.2.1的真实Android设备上进行测试
答案 0 :(得分:1)
您是否在AndroidManifest.xml
注册了广播接收器?
<receiver android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>