Getting NetworkOnMainThreadException creating socket in AsyncTask

how is possible that I am getting android.os.NetworkOnMainThreadException when I try to create a socket calling bulb.connectToHW() if I do it from the doInBackground() method of my asycTask?

This is the code of the AsyncTask:

 package com.example.bulbcontrol2;
import java.net.InetAddress;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.widget.TextView;

public class AsyncConnection extends AsyncTask<Object, String, String> {
    private TextView textV;
    private Context context;
    private String message;
    private Device bulb;

    public AsyncConnection(TextView textViewToUpdate,Context context)
    {
        this.textV = textViewToUpdate;
        this.context = context;
    }

    @Override
    protected String doInBackground(Object... params) {

        bulb = new Device((InetAddress) params[0],(Integer) params[1]); 

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("open_connection")) 
                {
                    System.out.println(bulb.connectToHW());
                    message = "Connected";  
                    System.out.println(bulb.dataTransferHW("hello"));
                    textV.setText(message);                                     
                }
                if (intent.getAction().equals("close_connection")) 
                {
                    message = "Disconnected";
                    System.out.println(bulb.dataTransferHW("bye"));
                    bulb.closeConexHW();
                }
            }
        };

        IntentFilter filter = new IntentFilter("open_connection");
        context.registerReceiver(receiver, filter);
        filter.addAction("close_connection");
        context.registerReceiver(receiver, filter);

        return message;
    }
/*    protected void onProgressUpdate(String... progress) {
        //textV.setText(progress[0]);
    }*/

 }

And this is the code of the UIThread :

package com.example.bulbcontrol2;

import java.net.InetAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity 
{   
    Intent broadcastIntent = new Intent();
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bulbActions();
    }

    public void bulbActions()
    {
        final ToggleButton buttonBulb = (ToggleButton) findViewById(R.id.ToggleBulb);
        final ToggleButton buttonLDR = (ToggleButton) findViewById(R.id.ToggleLDRValues);
        final TextView txtLDR = (TextView) findViewById(R.id.TxtLDRValues);
        byte [] hostBytes = new byte[] {(byte)192,(byte)168,(byte)0,(byte)12};
        int port = 5006;
        InetAddress host = null;

        try 
        {
            host = InetAddress.getByAddress(hostBytes);
        } 
        catch (UnknownHostException e) 
        {
            System.out.println("\nError with server address");
            e.printStackTrace();
        }   
        new AsyncConnection((TextView)findViewById(R.id.TxtLDRValues),this.getApplicationContext()).execute(host,port);     

        buttonBulb.setOnClickListener(new View.OnClickListener() 
        {
            @Override  
            public void onClick(View arg0) 
            {               
                if (buttonBulb.isChecked())
                {
                    System.out.println("Pulsado");
                    broadcastIntent.setAction("open_connection");
                    MainActivity.this.sendBroadcast(broadcastIntent);
                }   
                else
                {
                    System.out.println("NO Pulsado");
                    broadcastIntent.setAction("close_connection");
                    MainActivity.this.sendBroadcast(broadcastIntent);
                }
            }
        }); 
    }
}

Answers


Your doInBackground is just defining a BroadcastReceiver and registering it. All the code inside onReceive will run in the main thread when the system calls it following your onClick.

I don't know why you need a BroadcastReceiver if you're just triggering it from a button. Instead you could do the network stuff directly on your doInBackground and then actually start the AsyncTask inside onClick.

On a case you do need a BroadcastReceiver what you wanna do is start a service from onReceive and do all the network job in the service. After API11 you can also use goAsync() in the receiver as described here and start a Thread.


Need Your Help

Sails.js body contents when Content-Type is text/csv

node.js express sails.js

Do I need to do anything special to handle POST requests with a text-ish Content-Type?

Fixed header, footer with scrollable content

html css css3

How can I get fixed header, footer with scrollable content? Something like this page. I can look at the source to get the CSS, but I just want to know minimum CSS and HTML I need to get this working.