我正在编写一个从 bt 耳机捕获媒体按钮点击的应用程序。但是,由于清单文件中说明了我的接收器,我突然不再控制我的活动,我真正想做的是当有人按下耳机按钮时“按下”活动上的软件按钮.
我尝试了几种解决方案,但没有任何工作。这是我目前的状态
package com.siriforreq.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MediaButtonReceiver extends BroadcastReceiver{
private boolean gotMessage = false;
public MediaButtonReceiver(){
super();
}
public boolean isMessage(){
return this.gotMessage;
}
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("IN ON RECEIVE1");
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
System.out.println("GOT MEDIA BUTTON");
Intent startBroadcastIntent = new Intent(context, NetworkActivity.class);
startBroadcastIntent.setAction("com.siriforerq.activities.ACTION_LOL");
startBroadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
System.out.println("...sending broadcast");
context.sendBroadcast(startBroadcastIntent);
}
}
}
在上面的接收器中,我确实抓住了媒体按钮。但是从现在开始我应该去哪里更新我的活动呢?我现在要做的是发送另一个自定义广播并在活动中的另一个接收器中捕获它,但它似乎不起作用。这是我的活动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
mMediaReceiverCompName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
IntentFilter btCommunicationFilter = new IntentFilter();
btCommunicationFilter.setPriority(1000);
btCommunicationFilter.addAction("com.siriforerq.activities.ACTION_LOL");
catchButtonEvent = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Got broadcast yes");
//startTalkInteraction(); <- this is the method I want to call in the activity
}
};
registerReceiver(catchButtonEvent, btCommunicationFilter);
}
public void onResume() {
super.onResume();
mAudioManager.registerMediaButtonEventReceiver(mMediaReceiverCompName);
socketNetworkHelper = SocketNetworkHelper.getSocketNetworkHelper(ip, port);
setButtonStatus(true);
}
在上面的匿名接收器中,从 MediaButtonReceiver 发送的广播永远不会被调用,这是我现在的问题。我应该以另一种方式思考还是为什么我的 onReceive 在匿名接收器类触发器中没有?