1

我编写了一个 android 应用程序来接收蓝牙耳机事件,但是 onReceive() 没有被调用。虽然我不确定 ACTION_MEDIA_BUTTON 是用作事件还是不是这个事件。


实现接收器的示例代码:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class MediaButtonIntentReceiver extends BroadcastReceiver {

private static final String TAG = "MediaButtonIntentReceiver";
public MediaButtonIntentReceiver() {
    super();
    }


@Override
public void onReceive(Context context, Intent intent) {//OnReceive

    String intentAction = intent.getAction(); //getAction()
    Log.d(TAG, "onReceive called");
    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();
}
}



活动看起来像这样:

public class myactivity extends Activity {
    private static final String TAG ="Bluetooth_priority";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { //onCreate 
        super.onCreate(savedInstanceState);
        Log.d(TAG, "Oncreate called");
        setContentView(R.layout.main);
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
        filter.setPriority(1000); // set teh priority
        registerReceiver(r, filter); //register
    }
}



Manifest.xml 看起来像这样:

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

万一有人知道,请回复。即使将优先级设置为2147483647,它也不起作用。

4

1 回答 1

0

我认为您正在过滤错误的意图。我认为您想要的意图操作是 BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED

你可以参考http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html#ACTION_CONNECTION_STATE_CHANGED

于 2013-03-20T09:16:33.177 回答