在三星耳机Android系统中检测按钮按下

3
我将为您进行翻译:

我正在尝试通过BroadcastReciever检测原版三星耳机按钮的硬按。

代码很简单:

public class MediaButtonIntentReceiver extends BroadcastReceiver {

public MediaButtonIntentReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    String intentAction = intent.getAction();
    Toast.makeText(context, "Action: "+intentAction, Toast.LENGTH_SHORT).show(); 
    if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
        return;
    }
    Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show(); 
    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();
}

清单:

 <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".MediaButtonIntentReceiver" >
        <intent-filter android:priority="100000000000000" >
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
</application>

我已经在Galaxy S1(2个已root的设备,没有发生任何事情)和Galaxy NOTE上进行了测试(媒体已启动/停止并相应地更改了音量,但代码中没有发生任何事情...),在HTC上一切都正常。我99%确定这不是优先级问题,因为我已经多次更改它。
如果有人知道其中的问题,我会非常感激。 谢谢。Udi
2个回答

2
您还需要在AudioManager上调用registerMediaButtonEventReceiver才能接收事件。该状态将保持不变,直到其他内容调用registerMediaButtonEventReceiver()或者您调用unregisterMediaButtonEventReceiver()为止。

例如,像这样的活动:

public class MediaButtonActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName(
                                                                                                   this,
                                                                                                   MediaButtonIntentReceiver.class));
    }
}

这将使您的清单注册的MediaButtonIntentReceiver能够获取ACTION_MEDIA_BUTTON事件。


0

尝试关闭S-Voice,然后再次运行您的应用程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接