Reputation: 33
I'm new to Android programming. My application crashes while creating a socket. I added to the Manifest internet permission, and Wifi is on. I have a server on a PC waiting for the Android client; it works well with my other applications. I don't know where the problem with is this application. I'd appreciate any help.
Log errors
01-23 13:10:32.110: E/AndroidRuntime(4493): FATAL EXCEPTION: main
01-23 13:10:32.110: E/AndroidRuntime(4493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.usapp/com.example.usapp.Settings}: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1751)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1767)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1005)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Looper.loop(Looper.java:132)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.main(ActivityThread.java:4028)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invoke(Method.java:491)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.NativeStart.main(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): Caused by: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:901)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Stream.doInBackground(Stream.java:46)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Settings.onCreate(Settings.java:37)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1715)
01-23 13:10:32.110: E/AndroidRuntime(4493): ... 11 more
Java class
package com.example.usapp;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
public class Stream extends AsyncTask<Void, Void, Void>{
Bitmap image;
int frameCounter=0;
int checkCounterFPS=0;
long lastFpsTime=0;
double FPS;
protected Handler handler_bitmap, handlerdata;
boolean firstSetOfFPS=false;
double availableFPS;
double toleranceValue;
boolean firstFalseFPS = false;
byte[] datainput = new byte[1024];
Socket socket;
@Override
protected Void doInBackground(Void... params) {
Log.i("DUPA","po String doInBackground(String... params) ");
try {
Log.i("DUPA","przed socket");
socket = new Socket();
InetSocketAddress adres = new InetSocketAddress("192.168.1.50", 4444);
//adres.
socket.connect(adres);
//socket = new Socket("192.168.1.50", 4444);
Log.i("DUPA","po socket");
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
Log.i("DUPA","po socketconnected ");
/*
do {
try {
ByteBuffer buffer = ByteBuffer.allocate(9);
in.read(buffer.array());
byte[] bBuffer = new byte[9];
buffer.get(bBuffer, 0, 9);
int len = Integer.parseInt(new String(bBuffer,"US-ASCII"));
int bytesRecieved = 0;
ByteBuffer completeBuf;
completeBuf = ByteBuffer.allocate(len);
while (len > bytesRecieved) {
int inSize = in.available();
if (inSize > len- bytesRecieved) {
buffer = ByteBuffer.allocate(len- bytesRecieved);
bytesRecieved += len- bytesRecieved;
in.read(buffer.array());
completeBuf.put(buffer);
} else {
bytesRecieved += inSize;
buffer = ByteBuffer.allocate(inSize);
in.read(buffer.array());
completeBuf.put(buffer);
}
}
frameCounter++;
long delay = (long) (System.currentTimeMillis() - lastFpsTime);
if (delay > 1000) {
checkCounterFPS++;
FPS = (((double) frameCounter) / delay) * 1000;
handler_bitmap.post(new Runnable() {
public void run() {
///usunieto fps set text
}
});
frameCounter = 0;
lastFpsTime = System.currentTimeMillis();
}
if (checkCounterFPS >= 3 && firstSetOfFPS == true) {
checkCounterFPS = 0;
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
firstFalseFPS = true;
}
} else if (firstFalseFPS == true) {
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
// setSendText("FPS",(int) FPS);
firstFalseFPS = false;
}
}
//publishProgress(completeBuf);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad2");
}
} while (!socket.isInputShutdown() && !socket.isClosed()); //
// publishProgress("Status: Closed".getBytes());*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad3");
}
Log.i("AsyncTask", "doInBackground: Finished");
return null;
}
protected Bitmap onProgressUpdate(ByteBuffer... values) {
Log.i("DUPA","blad4");
return image = BitmapFactory.decodeByteArray(values[0].array(), 0,values[0].array().length);
}
}
Upvotes: 0
Views: 367
Reputation: 1988
As correctly pointed out by others, android does not allow networking operations on the main UI thread since Honeycomb and higher versions. I can see that you have created a class extending AsyncTask, which is a special class provided by android for doing background operations. You need to create a separate activity and trigger your AsyncTask from it. That way the code within doInBackground()
will execute in a separate thread and will not block your main activity.
eg., you can make your Stream
class an inner class to another activity add the following code to the onCreate()
method of the activity
Stream task = new Stream();
task.execute();
Upvotes: 1
Reputation: 20223
As @pingw33n mentioned in his comement, the Android network connection has to be done in an AsyncTask thread, not in the main thread. This worked in older versions of android but in the newest ones, your network connection can't be done in the main thread.
Upvotes: 0