Android - registerReceiver出错...... WifiManager

时间:2018-03-12 20:22:49

标签: android service broadcastreceiver wifimanager

逗人,

我正在开发一种服务(适用于旧的Android版本),它可以对传入的短信做出反应,并且应该提供有关检测到的wif的信息。

主要类是'

  

公共类IncomingSms扩展了BroadcastReceiver

声明的地方:

  

私有Context recContext;

其“Onreceive”内部是捕获不同传入短信的代码。当传入的SMS具有适当的角色时,会创建WifiManger:

public void onReceive(Context context, Intent intent){


    ......
    recContext = context;
    .........
    case wifilist:
        .........
        'wifimanager = (WifiManager) recContext.getSystemService(recContext.WIFI_SERVICE);' 
        ........
        SendLoc();
        .........

}

'SendLoc'是IncomingSMs的方法,其代码如下:

private void SendLoc() {

....
case wifilist:
            if (wifimanager.isWifiEnabled()) {
                    ....
                    scanWifiNetworks();
        ....}
   ...}

'scanWifiNetworks()'是IncomingSM的另一种方法,其代码如下:

 private void scanWifiNetworks(){
        if(wifimanager.startScan()){

            try{
            recContext.registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));}
            catch(Exception e){
                Toast.makeText(recContext, "catch de register receiver", Toast.LENGTH_LONG).show();
            }
        }
    }

wifi_receiver的代码也在IncomingSMs类中:

BroadcastReceiver wifi_receiver = new BroadcastReceiver() {
...

    public void onReceive(Context recontext, Intent intent) {

        Toast.makeText(recContext, "A onReceive ", Toast.LENGTH_LONG).show();
       ...}

}

无论使用'BroadcastReceiver wifi_receiver'的OnReceive方法中的不同代码,'recContext.registerReceiver(wifi_receiver,...'总是崩溃并被称为catch异常的消息。

我尝试使用与Activity中的按钮调用的相同的wifi检测代码,它可以正常工作。所以我确信我拥有正确的权限。也许不可能在另一个BroadcastReceiver类中创建一个接收器,或者存在上下文问题?

0 个答案:

没有答案