TCP连接期间应用程序崩溃

时间:2013-01-23 12:28:38

标签: java android eclipse android-asynctask tcpclient

我是Android编程的新手。我的应用程序在创建套接字时崩溃。我添加到Manifest互联网许可,Wifi开启了。我在PC上有一台等待Android客户端的服务器;它适用于我的其他应用程序。我不知道这个应用程序的问题在哪里。我很感激任何帮助。

记录错误

  

01-23 13:10:3​​2.110:E / AndroidRuntime(4493):致命异议:主要
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.usapp / com.example.usapp.Settings}:android.os.NetworkOnMainThreadException
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1751)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1767)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread.access $ 1500(ActivityThread.java:122)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1005)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.os.Handler.dispatchMessage(Handler.java:99)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.os.Looper.loop(Looper.java:132)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread.main(ActivityThread.java:4028)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at java.lang.reflect.Method.invokeNative(Native Method)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at java.lang.reflect.Method.invoke(Method.java:491)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:844)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at dalvik.system.NativeStart.main(Native Method)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):引起:android.os.NetworkOnMainThreadException
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at dalvik.system.BlockGuard $ WrappedNetworkSystem.connect(BlockGuard.java:368)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at java.net.Socket.connect(Socket.java:901)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at java.net.Socket.connect(Socket.java:844)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at com.example.usapp.Stream.doInBackground(Stream.java:46)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):at com.example.usapp.Settings.onCreate(Settings.java:37)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1715)
  01-23 13:10:3​​2.110:E / AndroidRuntime(4493):... 11更多

Java类

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);
  }
}

2 个答案:

答案 0 :(得分:1)

正如其他人正确指出的那样,自从Honeycomb及更高版本以来,android不允许在主UI线程上进行网络操作。我可以看到你创建了一个扩展AsyncTask的类,这是android为后台操作提供的一个特殊类。您需要创建一个单独的活动并从中触发AsyncTask。这样,doInBackground()中的代码将在单独的线程中执行,并且不会阻止您的主要活动。 例如,您可以将Stream类作为另一个活动的内部类添加以下代码到活动的onCreate()方法

Stream task = new Stream();
task.execute();

答案 1 :(得分:0)

正如@ pingw33n在他的演讲中提到的,Android网络连接必须在AsyncTask线程中完成,而不是在主线程中完成。这适用于较旧版本的android,但在最新版本中,您的网络连接无法在主线程中完成。