我写了一个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
}
}
<receiver android:name="MediaButtonIntentReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
如果有人知道这一点,请回复。即使设置优先级为2147483647,也不行。
答案 0 :(得分:0)
我认为你是在过滤错误的意图。您想要的意图操作是BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED