简体   繁体   English

Java套接字编程 - 在Android 4.1中无法运行?

[英]Java socket programming - Wont work in Android 4.1?

In my Android project I just have one Activity - "MainActivity.java". 在我的Android项目中,我只有一个Activity - “MainActivity.java”。 I added another class file in the same package "GetSocket.java". 我在同一个包“GetSocket.java”中添加了另一个类文件。

Functionality of GetSocket.java is it will return a string via Socket connection to a particular server hosted in a website. GetSocket.java的功能是它将通过Socket连接返回一个字符串到网站中托管的特定服务器。 GetSocket.java works just fine if run alone as a Java Application. 如果单独作为Java应用程序运行,GetSocket.java可以正常工作。

But when I call it using from the Android Activity, it doesn't return me the intended message, it just gets failed with an exception for which I'm unable to get StackTrace as well. 但是当我从Android Activity中调用它时,它并没有返回给我预期的消息,它只是因为异常而失败,我也无法获得StackTrace。

Mind you this is the outcome when ran in Android 4.1 version. 请注意,这是在Android 4.1版本中运行时的结果。

But the same code works in Android 2.2 and gets me the intended message. 但是相同的代码在Android 2.2中运行并且获得了预期的消息。

MainActivity.java MainActivity.java

public class MainActivity
{
TextView t= (TextView) getViewById(R.id.textView1);
//..
//some code
//..
String msg=GetSocket.getMessage();

//..
//some more code
//
}

GetSocket.java GetSocket.java

public class GetSocket
{
 public static String getMessage()
 {
  String b;
  Socket s=new Socket("<IP-Address",<Port-number>);
  InputStream i=s.getInputStream();
  int length=i.read(b)
  return b;
 }
}

Sorry about the late response. 对于迟到的回复感到抱歉。 Found the problem to my solution. 发现我的解决方案的问题。 From 4.0 Android doesn't allow socket programming through the UI thread. 从4.0开始,Android不允许通过UI线程进行套接字编程。 I used Async Task to hand the socket in a separate background thread. 我使用Async Task在单独的后台线程中处理套接字。 It worked. 有效。

检查你的清单上网权限:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM