tengo una Raspberry mandando unos datos a mi APP Android y la única forma en la que me funciona es la APP siguiente:
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();
}
}
Cuando yo quiero que solo reciba los datos cuando pase por el while(comprobar)
.
Este es el Intent Service en el que tiene que recibir la información.
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;
}
}
}
}
Simplemente se conecta a la raspberry y mientras esta conectada a esta quiero que actualice los datos cada 10 segundos pero si pongo lo primero sin el Thread y el se me para la app en el
clientsocket.receive(recv_packet);
String receivedstring = new String(recv_packet.getData());
y me da este 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)