简体   繁体   中英

Java socket programming - Wont work in Android 4.1?

In my Android project I just have one Activity - "MainActivity.java". I added another class file in the same package "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 works just fine if run alone as a Java Application.

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.

Mind you this is the outcome when ran in Android 4.1 version.

But the same code works in Android 2.2 and gets me the intended message.

MainActivity.java

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

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

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. I used Async Task to hand the socket in a separate background thread. It worked.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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