title: MQTT Service error "socket failed: EPERM"
body: <p>this is my class for MQTTCONECTION</p>
  <pre><code> public class MQTTService extends Service {
          private static final String TAG = &quot;MQTTService&quot;;
          private static boolean hasWifi = false;
          private static boolean hasMmobile = false;
          private Thread thread;
          private ConnectivityManager mConnMan;
          private volatile IMqttAsyncClient mqttClient;
          private String deviceId;
  
      class MQTTBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              IMqttToken token;
              boolean hasConnectivity = false;
              boolean hasChanged = false;
              NetworkInfo infos[] = mConnMan.getAllNetworkInfo();
  
              for (int i = 0; i &lt; infos.length; i++){
                  if (infos[i].getTypeName().equalsIgnoreCase(&quot;MOBILE&quot;)){
                      if((infos[i].isConnected() != hasMmobile)){
                          hasChanged = true;
                          hasMmobile = infos[i].isConnected();
                      }
                      Log.d(TAG, infos[i].getTypeName() + &quot; is &quot; + infos[i].isConnected());
                  } else if ( infos[i].getTypeName().equalsIgnoreCase(&quot;WIFI&quot;) ){
                      if((infos[i].isConnected() != hasWifi)){
                          hasChanged = true;
                          hasWifi = infos[i].isConnected();
                      }
                      Log.d(TAG, infos[i].getTypeName() + &quot; is &quot; + infos[i].isConnected());
                  }
              }
  
              hasConnectivity = hasMmobile || hasWifi;
              Log.v(TAG, &quot;hasConn: &quot; + hasConnectivity + &quot; hasChange: &quot; + hasChanged + &quot; -                  &quot;+(mqttClient == null || !mqttClient.isConnected()));
              if (hasConnectivity &amp;&amp; hasChanged &amp;&amp; (mqttClient == null || !mqttClient.isConnected())) {
                  //Log.d(TAG, &quot;Llama a la función doConnect&quot;);
                  doConnect();
  
  
              } else if (!hasConnectivity &amp;&amp; mqttClient != null &amp;&amp; mqttClient.isConnected()) {
                  Log.d(TAG, &quot;doDisconnect()&quot;);
                  try {
                      token = mqttClient.disconnect();
                      token.waitForCompletion(1000);
                  } catch (MqttException e) {
                      e.printStackTrace();
                  }
              }
          }
      };
  
      public class MQTTBinder extends Binder {
          public MQTTService getService(){
              return MQTTService.this;
          }
      }
  
      @Override
      public void onCreate() {
          IntentFilter intentf = new IntentFilter();
          setClientID();
          intentf.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
          registerReceiver(new MQTTBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
          mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
      }
  
      @Override
      public void onConfigurationChanged(Configuration newConfig) {
          Log.d(TAG, &quot;onConfigurationChanged()&quot;);
          android.os.Debug.waitForDebugger();
          super.onConfigurationChanged(newConfig);
  
      }
  
      private void setClientID(){
          WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
          WifiInfo wInfo = wifiManager.getConnectionInfo();
          deviceId = wInfo.getMacAddress();
          if(deviceId == null){
              deviceId = MqttAsyncClient.generateClientId();
          }
      }
  
      private void doConnect(){
  
          IMqttToken token;
          MqttConnectOptions options = new MqttConnectOptions();
          options.setCleanSession(true);
          //StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
  
          try {
              mqttClient = new MqttAsyncClient(&quot;tcp://192.168.0.9:1883&quot;, deviceId, new MemoryPersistence());
              token = mqttClient.connect();
              token.waitForCompletion(3500);
              mqttClient.setCallback(new MqttEventCallback());
              token = mqttClient.subscribe(&quot;test&quot;, 0);
              token.waitForCompletion(5000);
              token.setActionCallback(new IMqttActionListener() {
  
                  @Override
                  public void onSuccess(IMqttToken asyncActionToken) {
                      Log.d(TAG, &quot;Si se conecto&quot;);
                      /*String mensaje = &quot;Conchita&quot;;
                      byte[] mensajeB = mensaje.getBytes(UTF_8);
                      MqttMessage mqttMessage = new MqttMessage(mensajeB);
                      try {
                          mqttClient.publish(&quot;test&quot;, mqttMessage);
                      } catch (MqttException e) {
                          e.printStackTrace();
                      }*/
                  }
                  @Override
                  public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                      Log.d(TAG, &quot;Que nel&quot;);
                  }
              });
          } catch (MqttSecurityException e) {
              e.printStackTrace();
          } catch (MqttException e) {
  
              switch (e.getReasonCode()) {
  
                  case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
                      Log.d(TAG, &quot;The broker was not available to handle the request.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_ALREADY_DISCONNECTED:
                      Log.d(TAG, &quot;The client is already disconnected.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_CLOSED:
                      Log.d(TAG, &quot;The client is closed - no operations are permitted on the client in this state.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_DISCONNECT_PROHIBITED:
                      Log.d(TAG, &quot;Thrown when an attempt to call MqttClient.disconnect() has been made from within a method on MqttCallback.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_DISCONNECTING:
                      Log.d(TAG, &quot;The client is currently disconnecting and cannot accept any new work.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_EXCEPTION:
                      Log.d(TAG, &quot;Client encountered an exception.&quot;);
                      System.out.println(&quot;Cause of Exception: &quot;
                              + e.getCause());
                      break;
                  case MqttException.REASON_CODE_CLIENT_NOT_CONNECTED:
                      Log.d(TAG, &quot;The client is not connected to the server.&quot;);
                      break;
                  case MqttException.REASON_CODE_CLIENT_TIMEOUT:
                      Log.d(TAG, &quot;Client timed out while waiting for a response from the server.&quot;);
                      break;
                  case MqttException.REASON_CODE_CONNECT_IN_PROGRESS:
                      Log.d(TAG, &quot;A connect operation in already in progress, only one connect can happen at a time.&quot;);
                      break;
                  case MqttException.REASON_CODE_CONNECTION_LOST:
                      Log.d(TAG, &quot;The client has been unexpectedly disconnected from the server.&quot;);
                      break;
                  case MqttException.REASON_CODE_DISCONNECTED_BUFFER_FULL:
                      Log.d(TAG, &quot;The Client has attempted to publish a message whilst in the 'resting' / &quot;);
                      break;
                  case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
                      Log.d(TAG, &quot;Client encountered an exception.&quot;);
                      break; //
                  case MqttException.REASON_CODE_INVALID_CLIENT_ID:
                      Log.d(TAG, &quot;The server has rejected the supplied client ID&quot;);
                      break;
                  case MqttException.REASON_CODE_INVALID_MESSAGE:
                      Log.d(TAG, &quot;Protocol error: the message was not recognized as a valid MQTT       packet.&quot;);
                      break;
                  case MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION:
                      Log.d(TAG, &quot;The protocol version requested is not supported by the server.&quot;);
                      break;
                  case MqttException.REASON_CODE_MAX_INFLIGHT:
                      Log.d(TAG, &quot;A request has been made to send a message but the maximum number of inflight messages has already been reached.&quot;);
                      break;
                  case MqttException.REASON_CODE_NO_MESSAGE_IDS_AVAILABLE:
                      Log.d(TAG, &quot;Internal error, caused by no new message IDs being available.&quot;);
                      break;
                  case MqttException.REASON_CODE_NOT_AUTHORIZED:
                      Log.d(TAG, &quot;ot authorized to perform the requested operation&quot;);
                      break;//--
                  case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
                      Log.d(TAG, &quot;Unable to connect to server&quot;);
                      break;
                  case MqttException.REASON_CODE_SOCKET_FACTORY_MISMATCH:
                      Log.d(TAG, &quot;Server URI and supplied SocketFactory do not match.&quot;);
                      break;
                  case MqttException.REASON_CODE_SSL_CONFIG_ERROR:
                      Log.d(TAG, &quot;SSL configuration error.&quot;);
                      break;
                  case MqttException.REASON_CODE_SUBSCRIBE_FAILED:
                      Log.d(TAG, &quot;Error from subscribe - returned from the server.&quot;);
                      break;
                  case MqttException. REASON_CODE_TOKEN_INUSE:
                      Log.d(TAG, &quot;A request has been made to use a token that is already associated with another action.&quot;);
                      break;
                  case MqttException.REASON_CODE_UNEXPECTED_ERROR:
                      Log.d(TAG, &quot;An unexpected error has occurred.&quot;);
                      break;//--
                  case MqttException.REASON_CODE_WRITE_TIMEOUT:
                      Log.d(TAG, &quot;Client timed out while waiting to write messages to the server.&quot;);
                      break;//--
                  /*case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
                      Log.d(TAG, &quot;c&quot; +e.getMessage());
                      e.printStackTrace();
                      break;
                  case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
                      Intent i = new Intent(&quot;RAISEALLARM&quot;);
                      i.putExtra(&quot;ALLARM&quot;, e);
                      Log.d(TAG, &quot;b&quot;+ e.getMessage());
                      break;*/
                  default:
                      Log.e(TAG, &quot;a_&quot; + e.getMessage());
              }
          }
      }
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          Log.v(TAG, &quot;onStartCommand()&quot;);
          return START_STICKY;
      }
  
      private class MqttEventCallback implements MqttCallback {
  
          @Override
          public void connectionLost(Throwable arg0) {
  
  
          }
  
          @Override
          public void deliveryComplete(IMqttDeliveryToken arg0) {
  
          }
  
          @Override
          @SuppressLint(&quot;NewApi&quot;)
          public void messageArrived(String topic, final MqttMessage msg) throws Exception {
              Log.i(TAG, &quot;Message arrived from topic&quot; + topic);
              Handler h = new Handler(getMainLooper());
              h.post(new Runnable() {
                  @Override
                  public void run() {
                      Intent launchA = new Intent(MQTTService.this, MainActivity.class);
                      launchA.putExtra(&quot;message&quot;, msg.getPayload());
                      //TODO write somethinkg that has some sense
                      if(Build.VERSION.SDK_INT &gt;= 11){
                          launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_NO_ANIMATION);
                      } /*else {
                          launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                      }*/
                      startActivity(launchA);
                      Toast.makeText(getApplicationContext(), &quot;MQTT Message:\n&quot; + new String(msg.getPayload()), Toast.LENGTH_SHORT).show();
                  }
              });
          }
      }
  
      public String getThread(){
          return Long.valueOf(thread.getId()).toString();
      }
  
      @Override
      public IBinder onBind(Intent intent) {
          Log.i(TAG, &quot;onBind called&quot;);
          return null;
      }
  
      }
  </code></pre>
  <p>And this is my MainActivity:</p>
  <pre><code>    public class MainActivity extends AppCompatActivity {
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          Intent mymqttservice_intent = new Intent(this, MQTTService.class);
          startService(mymqttservice_intent);
      }
      }
  </code></pre>
  <p>And manifest file:</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
      package=&quot;com.example.serviciomqtt_2&quot;&gt;
  
      &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;
      &lt;uses-permission android:name=&quot;android.permission.ACCESS_INTERNET&quot;/&gt;
  
      &lt;application
          android:allowBackup=&quot;true&quot;
          android:icon=&quot;@mipmap/ic_launcher&quot;
          android:label=&quot;@string/app_name&quot;
          android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
          android:supportsRtl=&quot;true&quot;
          android:usesCleartextTraffic=&quot;true&quot;
          android:theme=&quot;@style/AppTheme&quot;&gt;
  
          &lt;service
              android:enabled=&quot;true&quot;
              android:name=&quot;MQTTService&quot;
              /&gt;
  
  
          &lt;activity android:name=&quot;.MainActivity&quot;&gt;
              &lt;intent-filter&gt;
                  &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
  
                  &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
              &lt;/intent-filter&gt;
          &lt;/activity&gt;
      &lt;/application&gt;
  
  &lt;/manifest&gt;
  </code></pre>
  <p>Iam using API 29, also, MOsquitto mqtt broker is active</p>
  <p><a href="https://i.stack.imgur.com/RHRW4.png" rel="nofollow noreferrer">Status Mosquitto Broker</a></p>
  <p>When i run the app I have the next error:</p>
  <p>I/System.out: Cause of Exception: java.net.SocketException: socket failed: EPERM (Operation not permitted)</p>