我正在尝试实现一个广播接收器,它应该从后台运行的服务接收 Intent,但是它不起作用。
在我的主要活动中,我只是绑定服务并通过onClick
按钮启动它。
在我的SpeechRecognizer
服务类中,我创建了一个新的BroadcastReceiver
(参见下面的代码)。
public void onCreate() {
Log.d(TAG, "onCreate");
if (SpeechRecognizer.isRecognitionAvailable(this)){ //check if a SpeechRecognizer is available
this.sr = SpeechRecognizer.createSpeechRecognizer(this);
this.sr.setRecognitionListener(new listener());
commandsReceiver = new CommandsReceiver();
ConnectivityManager cm =(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
testfilter = new IntentFilter();
registerReceiver(commandsReceiver,testfilter);
} else {
Toast.makeText(this,"Please install a SpeechRecognizer on your system.", Toast.LENGTH_LONG).show(); //alert if speech-recognizer is not installed on the device
Log.d(TAG, "no SpeechRecognizer available");
this.onDestroy();
}
}
在我的onResult
我这样做:
Intent intent = new Intent();
intent.setAction(CommandsReceiver.TEST);
sendBroadcast(intent);
在我的中CommandsReceiver
,我收到了一条简单String
的日志消息:
public class CommandsReceiver extends BroadcastReceiver {
public static final String TEST = "de.speech.TEST_INTENT";
@Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadCastReceiver", "Intent received"+intent);
}
}
但是我没有收到Log.d()
消息。
我希望你能帮助我。