2

我正在尝试实现一个广播接收器,它应该从后台运行的服务接收 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()消息。

我希望你能帮助我。

4

1 回答 1

2

似乎您正在创建一个没有任何操作的 IntentFilter

testfilter = new IntentFilter();

代替,

testfilter = new IntentFilter(CommandsReceiver.TEST);

所以,注册您的广播使用,

testfilter = new IntentFilter(CommandsReceiver.TEST);
registerReceiver(commandsReceiver,testfilter);
于 2012-09-10T07:57:12.423 回答