我想registerReceiver
像BluetoothDevice类事件ACTION_ACL_CONNECTED
, ACTION_ACL_DISCONNECTED
。
但在我使用的是类registerReceiver
不会扩展Activity
类,也没有Service
类-所以我传递Context
的那类和注册接收机如下
context.registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
context.registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
和处理事件如下
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// do some stuff
}
}
};
不过,当设备连接或断开我不能追踪是我的意思是ActionFoundReceiver
不能被调用
我试图通过解决这个问题,但我真的不知道如何安全是这一点,正是在这样的情况下,或者不是一个好的做法。
如果任何人有更好的ANS随意张贴
context.getApplicationContext().registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
这里是一个草图BroadcastReceiver
为我的作品。
你有一些类MyBroadcastReceiver
做所有的工作。
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// do some stuff
}
}
}
MyBroadcastReceiver
在托管MyClass
(这不是一个活动或服务)
public class MyClass {
private BroadcastReceiver myReceiver = null;
public MyClass(Context context) {
myReceiver = new MyBroadcastReceiver();
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_CONNECTED));
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_DISCONNECTED));
context.registerReceiver(myReceiver, new IntentFilter(
BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
}
public void unregisterReceiver(Context context) {
context.unregisterReceiver(this);
}
}
MyClass
生存期由控制MyActivity
(或MyService
)。
public class MyActivity extends Activity {
private MyClass myClass = null;
@Override
public void onResume(Bundle savedInstanceState) {
super.onResume(savedInstanceState);
// ...
myClass = new MyClass(this);
}
@Override
public void onPause() {
if (myClass != null) {
myClass.unregisterReceiver(this);
myClass = null;
}
super.onPause();
}
}
这也可以onCreate
/ onDestroy
或服务中。
我有一些类似的问题,我有发来的短信接收器,我注册了,但从来没有所谓。 我试图这样做,也从来没有所谓的
actionfounder= new ActionFounderReceiver();
context.registerReceiver(actionfounder , new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
那么,什么是我的惊喜,它被称为当我这样注册它:
context.registerReceiver(new ActionFoundReceiver() , new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
而内部类:
class ActionFoundReceiver extends BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// do some stuff
}
}
}
只是当我得到一个全新的实例,它的作品。
希望这可以帮助。