如何在扩展BroadcastReceiver的类中注册广播接收器?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在扩展BroadcastReceiver的类中注册广播接收器?相关的知识,希望对你有一定的参考价值。
我已经看到了关于BroadcastReceiver
注册的所有例子,所有这些例子都注册了接收器而没有扩展BroadcastReceiver
类。但我有以下代码
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.UUID;
public class SearchBLDev extends BroadcastReceiver {
private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
private ArrayAdapter BTArrayAdapter;
private ListView BTListView;
private BluetoothDevice BTD;
public UUID myUUID;
IntentFilter filter = new IntentFilter();
public void discoveryStart()
{
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(SearchBLDev, filter) //PROBLEM OCCURS HERE
}
@Override
public void onReceive(Context context, Intent intent)
{}
}
我可以使用registerReceiver方法注册一个Receiver。它显示错误。
感谢您的时间。
答案
您需要一个Context来调用registerReceiver(this, filter)
,因此您应该将其作为参数传递。
public void discoveryStart(Context context)
{
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
context.registerReceiver(this, filter) //PROBLEM OCCURS HERE
}
然后你可以从你的Activity
调用它:
SearchBLDev broadcastReceiver = new SearchBLDev();
broadcastReceiver.discoveryStart(this);
另一答案
您是否尝试将接收器添加到清单中?你在哪里初始化这个broadcastReceiver?
以上是关于如何在扩展BroadcastReceiver的类中注册广播接收器?的主要内容,如果未能解决你的问题,请参考以下文章
AlarmManager 不调用 BroadcastReceiver