Problem receiving a socket on android

1

I have a Raspberry sending some data to my Android APP and the only way it works for me is the following APP:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
             new Thread(new Runnable() {
                public void run() {
                try {
                    DatagramSocket clientsocket= new DatagramSocket(5005);
                    byte[] receivedata = new byte[30];
                    while(true) {
                        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
                        Log.d("UDP", "S: Receiving...");
                        clientsocket.receive(recv_packet);
                        String receivedstring = new String(recv_packet.getData());
                        Log.d("UDP", " Received String: " + receivedstring);
                        InetAddress ipaddress = recv_packet.getAddress();
                        int port = recv_packet.getPort();
                        Log.d("UDP", "IPAddress : " + ipaddress.toString());
                        Log.d("UDP", "Port : " + Integer.toString(port));
                    }
                } catch (SocketException e) {
                    Log.e("UDP", "Socket Error", e);
                } catch (IOException e) {
                    Log.e("UDP", "IO Error", e);
                }
            }
        }).start();

    }
}

When I want you to only receive the data when I pass the while(comprobar) . This is the Intent Service in which you have to receive the information.

public class MiIntentService extends IntentService {

    public boolean actualizando = true;
    private WifiManager wifiManager;
    private WifiInfo wifiInfo;
    private WifiConfiguration wifiConfig = new WifiConfiguration();
    private String connectedID;
    private String ssid = "UBIC";
    private String myssid = "\"UBIC\"";
    private String key = "sistemaUBIC";


    public MiIntentService() {
        super("MiIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        while(actualizando) {
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
                esperar(5);
            }
            wifiInfo = wifiManager.getConnectionInfo();
            connectedID = wifiInfo.getSSID();
            if (!comprobar()) {
                connect();
                Log.d("Service", "conectando");
                esperar(10);
                wifiInfo = wifiManager.getConnectionInfo();
                connectedID = wifiInfo.getSSID();
            }

            if (comprobar()) {
                while(comprobar()) {

                    Log.d("Service", "Recibiendo coordenadas");
                    //RECIBIR DATOS

                    esperar(10);
                    wifiInfo = wifiManager.getConnectionInfo();
                    connectedID = wifiInfo.getSSID();
                }
            }
            esperar(60*5);

        }
    }
    public boolean comprobar(){
        if(connectedID.equals(myssid)){
            return true;
        }else {
            return false;
        }
    }

    public void esperar(int segundos) {

        try {
            Thread.sleep(segundos*1000);
        } catch (Exception e){
            Log.d("Service","esperar ha fallado");
        }
    }
    public void connect(){
        wifiConfig.SSID=String.format("\"%s\"",ssid);
        wifiConfig.preSharedKey = String.format("\"%s\"", key);
        wifiManager.addNetwork(wifiConfig);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list){
            if(i.SSID != null && i.SSID.equals(myssid)){
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId,true);
                wifiManager.reconnect();
                break;
            }
        }
    }


}

It simply connects to the raspberry and while it is connected to this I want it to update the data every 10 seconds but if I put the first one without the Thread and the one stops me the app in the

clientsocket.receive(recv_packet);
String receivedstring = new String(recv_packet.getData());

and I get this error

06-12 17:55:44.186 6961-6961/com.example.hector.conexionconsockets E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                     Process: com.example.hector.conexionconsockets, PID: 6961
                                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hector.conexionconsockets/com.example.hector.conexionconsockets.MainActivity}: android.os.NetworkOnMainThreadException
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
                                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:157)
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5551)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                                      Caused by: android.os.NetworkOnMainThreadException
                                                                                         at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
                                                                                         at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:249)
                                                                                         at libcore.io.IoBridge.recvfrom(IoBridge.java:549)
                                                                                         at java.net.PlainDatagramSocketImpl.doRecv(PlainDatagramSocketImpl.java:163)
                                                                                         at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:171)
                                                                                         at java.net.DatagramSocket.receive(DatagramSocket.java:274)
                                                                                         at com.example.hector.conexionconsockets.MainActivity.onCreate(MainActivity.java:31)
                                                                                         at android.app.Activity.performCreate(Activity.java:6272)
                                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494) 
                                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:157) 
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356) 
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                         at android.os.Looper.loop(Looper.java:148) 
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5551) 
                                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
    
asked by wasous 12.06.2017 в 18:16
source

1 answer

1

The problem is defined here:

Caused by: android.os.NetworkOnMainThreadException                                                                                        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)

This is a question where you have a similar problem, you should not perform operations on the main thread.

Error android.os. NetworkOnMainThreadException in using Android HttpURLConnection

I suggest one of the ways to avoid this problem, use runOnUiThread :

  runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {  
               proceso(); //Realizar aquí tu proceso!                    

            } catch (Exception e) {
                Log.e("Error", "Exception: " + e.getMessage());
            }
        }
    });

This would be the way to implement it in your code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


  runOnUiThread(new Runnable() {
        @Override
        public void run() {

                try {
                    DatagramSocket clientsocket= new DatagramSocket(5005);
                    byte[] receivedata = new byte[30];
                    while(true) {
                        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
                        Log.d("UDP", "S: Receiving...");
                        clientsocket.receive(recv_packet);
                        String receivedstring = new String(recv_packet.getData());
                        Log.d("UDP", " Received String: " + receivedstring);
                        InetAddress ipaddress = recv_packet.getAddress();
                        int port = recv_packet.getPort();
                        Log.d("UDP", "IPAddress : " + ipaddress.toString());
                        Log.d("UDP", "Port : " + Integer.toString(port));
                    }
                } catch (SocketException e) {
                    Log.e("UDP", "Socket Error", e);
                } catch (IOException e) {
                    Log.e("UDP", "IO Error", e);
                }

         }
      });


    }
}
    
answered by 12.06.2017 / 18:43
source