NetworkChange广播接收器

时间:2016-02-08 15:57:30

标签: android service broadcastreceiver mqtt

我正在使用服务中的以下工作代码运行MqttService

public void reconnect()
{

    try
    {         
        // try to connect
        String id;
        id=Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID);
        MqttConnectOptions conn_opts= new MqttConnectOptions();
        conn_opts.setCleanSession(true);
        conn_opts.setKeepAliveInterval(3600);
        conn_opts.setUserName(username);
        conn_opts.setPassword(password);
        mqttClient = new MqttClient(BROKER_URL, id, new MemoryPersistence());
        mqttClient.setCallback(this);
        mqttClient.connect(conn_opts);

              //Subscribe to all subtopics of homeautomation
        mqttClient.subscribe(TOPIC);

       // connectionStatus = MQTTConnectionStatus.CONNECTED;
        // inform the app that the app has successfully connected
        //broadcastServiceStatus("Connected");

    }
    catch (MqttPersistenceException e)
    {            
       // connectionStatus = MQTTConnectionStatus.NOTCONNECTED_UNKNOWNREASON;
       // broadcastServiceStatus("Unable to connect");     

    }
    catch (MqttSecurityException e)
    {            
       // connectionStatus = MQTTConnectionStatus.NOTCONNECTED_UNKNOWNREASON;
       // broadcastServiceStatus("Unable to connect");     

    }
    catch (MqttException e)
    {

    }


}`  

但是当这个代码在内部类广播接收器中执行时注册为:

netConnReceiver = new NetworkConnectionIntentReceiver();   
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netConnReceiver, intentFilter);

它总是崩溃。 这是简单的BroadcastReceiver代码:

private class NetworkConnectionIntentReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context ctx, Intent intent) 
    {
        // we protect against the phone switching off while we're doing this
        //  by requesting a wake lock - we request the minimum possible wake 
        //  lock - just enough to keep the CPU running until we've finished
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTTService");
        wl.acquire();

        if (isOnline() && mqttClient!=null) 
        {
            reconnect();
        }

        wl.release(); 
    }
}

我错过了什么?广播接收者必须是内部阶级。 我尝试了许多不同的解决方案但没有取得任何成功。

编辑:

02-16 17:49:56.270:E / AndroidRuntime(10554):FATAL EXCEPTION:main 02-16 17:49:56.270:E / AndroidRuntime(10554):进程:net.sprintbg.android.iptv,PID :10554 02-16 17:49:56.270:E / AndroidRuntime(10554):java.lang.RuntimeException:在net.sprintbg中接收广播Intent {act = android.net.conn.CONNECTIVITY_CHANGE flg = 0x4000010(has extras)}时出错.android.iptv.MQTTService $ NetworkConnectionIntentReceiver @ 94b35a4

如果我评论reconnect()总是会很完美。看来,当我在BroadcastReceiver外面打电话时,有什么想法缺失?此致

0 个答案:

没有答案