我正在编写一个应用程序,它可以从bt-headset中获取媒体按钮点击。但是,由于我的接收器在清单文件中声明,我突然无法控制我的活动,我真正想做的是当有人按下耳机按钮时“按下”活动上的软件按钮
我尝试了几种解决方案但没有任何工作要做。这是我目前的状态
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不会在匿名接收器类触发器中?
答案 0 :(得分:4)
正如在文档中可以看到的那样,您使用的构造函数Intent(class,context)
为特定组件创建了Intent
。相反,您应该像这样构建Intent
:
Intent startBroadcastIntent = new Intent();
startBroadcastIntent.setAction("com.siriforerq.activities.ACTION_LOL");
startBroadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);