0

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

记录错误

01-23 13:10:32.110: E/AndroidRuntime(4493): 致命异常: main
01-23 13:10:32.110: E/AndroidRuntime(4493): java.lang.RuntimeException: 无法启动活动 ComponentInfo{com. example.usapp/com.example.usapp.Settings}:android.os.NetworkOnMainThreadException
01-23 13:10:32.110:E/AndroidRuntime(4493):在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1751)
01 -23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1767)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app .ActivityThread.access$1500(ActivityThread.java:122)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1005)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.os.Handler.dispatchMessage(Handler.java:99)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android. os.Looper.loop(Looper.java:132)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app.ActivityThread.main(ActivityThread.java:4028)
01-23 13:10: 32.110: E/AndroidRuntime(4493): 在 java.lang.reflect.Method.invokeNative(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 java.lang.reflect.Method.invoke( Method.java:491)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
01-23 13:10: 32.110: E/AndroidRuntime(4493): 在 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): 引起:android.os .NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
01-23 13:10:32.110: E/AndroidRuntime(4493) : 在 dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl .java:208)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 java.net.Socket.connect(Socket.java:901)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 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): 在 com.example.usapp.Settings.onCreate(Settings.java:37)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app.Instrumentation .callActivityOnCreate(Instrumentation.java:1048)
01-23 13:10:32.110: E/AndroidRuntime(4493): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1715)
01-23 13:10:32.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);
  }
}
4

2 回答 2

1

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

Stream task = new Stream();
task.execute();
于 2013-01-23T13:55:59.873 回答
0

正如@pingw33n 在他的评论中提到的,Android 网络连接必须在 AsyncTask 线程中完成,而不是在主线程中。这在旧版本的 android 中有效,但在最新版本中,您的网络连接无法在主线程中完成。

于 2013-01-23T12:39:09.353 回答