我有一个带单键的耳机,按下按钮时想要做一个简单的Toast.
现在我有以下代码:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
@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) {
// do something
Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();
}
abortBroadcast();
}
}
Run Code Online (Sandbox Code Playgroud)
我的主要活动如下:
public class mainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void …Run Code Online (Sandbox Code Playgroud)