使用registerReceiver非活动和非服务类 [英] use registerReceiver for non activity and non service class

查看:199
本文介绍了使用registerReceiver非活动和非服务类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图 registerReceiver 的BluetoothDevice类事件,如 ACTION_ACL_CONNECTED ACTION_ACL_DISCONNECTED

I am trying to registerReceiver for BluetoothDevice events like ACTION_ACL_CONNECTED , ACTION_ACL_DISCONNECTED.

但类中,我使用 registerReceiver 不延活动类和服务类 - 所以我想过去上下文这个类和注册接收器如下:

But the class in which I am using registerReceiver does not extend Activity class nor Service class - so I am passing Context to that class and registering receiver as follows

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 是不是能得到所谓

推荐答案

我试图用解决这个问题,但我真的不知道如何安全是这一点,正是在这样的情况下,或者不是一个好的做法。

I tried to solve it by using , but i really don't know how safe is this and it is a good practice in this case or not.

如果任何人有更好的答随意张贴

if anyone has a better ans feel free to post

context.getApplicationContext().registerReceiver(ActionFoundReceiver, 
                  new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

这篇关于使用registerReceiver非活动和非服务类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆