I defined connection variable in top of the main class:
private XMPPConnection connection;
I am connecting to server with following code:
public void connect(final String username,final String password) {
Thread t=new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig=new ConnectionConfiguration("server ip", 5222,"localhost");
XMPPConnection connection=new XMPPTCPConnection(connConfig);
try{
connection.connect();
}catch(XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username,password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setConnection(connection);
}
});
t.start();
}
You see I am using thread for this operation.And if connection was successful setConnection method is calling.
setConnection method:
public void setConnection(XMPPConnection connection) {
this.connection=connection;
if (connection != null) {
//Other stuff
....
So,I am setting connection variable inside thread.But when I want to disconnect from server i am getting crash report.
Disconnect code:
try{
connection.disconnect();
}catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Report:
01-27 14:14:05.162: E/XMPPConnection(3160): Error in listener while closing connection
01-27 14:14:05.162: E/XMPPConnection(3160): android.os.NetworkOnMainThreadException
01-27 14:14:05.162: E/XMPPConnection(3160): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-27 14:14:05.162: E/XMPPConnection(3160): at java.net.InetAddress.getLocalHost(InetAddress.java:365)
01-27 14:14:05.162: E/XMPPConnection(3160): at org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy.<init>(Socks5Proxy.java:108)
I know this error.Android doesn't allow to use network operations from ui thread.But I already set connection inside another thread.Why do i need one more thread for disconnect operation ?
I followed this tutorial:http://developer.samsung.com/technical-doc/view.do?v=T000000119
And in this tutorial they didn't use another thread for disconnect.Why I am getting this error ?
Using you code which you have posted. define strict mode thread policy permission in onCreate method of Activity or Application
Assuming you have given INTERNET permission in manifest
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
If you dont wants to use the code which you have posted thn alternate solutions for that below i hve mentioned
Use Async task for the Network related operation or long process related
public class MyActivity extends Activity {
XMPPConnection connection;
private String username;
private String password;
public void connect(final String username, final String password) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class XMPPConnection extends AsyncTask<Void, Void, Void> {
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... params) {
connect(username, password);
return null;
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// from here update the ui and make ui related changes once
// onpostExecute is called
setConnection(connection);
}
}
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.test_layout);
username = "username#chat.abc.com";
password = "1234567";
new XMPPConnection().execute();
}
}
also Please check this
For async and ui changes , network related operation on main thread related please check this
and make sure setConnection(XMPPConnection connection) you are not doing any UI update related things..
OR you can also try
XMPPTCPConnection connection;
#Override
protected void onResume() {
super.onResume();
connect(LOGGED_USERNAME,"pass");
}
#Override
public void onPause() {
super.onPause();
try{
connection.disconnect();
}catch (SmackException e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
setConnection(connection);
}
};
public void connect(final String username, final String password) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"server ip", 5222, "localhost");
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (XMPPException ex) {
setConnection(null);
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection.login(username, password);
} catch (SaslException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessageAtTime(0, 1000);
}
});
t.start();
}
public void setConnection(XMPPTCPConnection connection) {
this.connection=connection;
if (connection != null) {
....
Related
I use a bluetooth_access Async task to establish a connection and I need continue to use the input stream and out stream of the bluetooth socket I established.
The issue I having is when I clicked button1 or button2, it sometimes (not all the times) cause Software caused connection abort. It got tripped on out.write(bytes) when clicked.
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)this.findViewById(R.id.button1);
button2 = (Button)this.findViewById(R.id.button2);
button3 = (Button)this.findViewById(R.id.button3);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
try {
for (int i = 0; i < 3; i++) {
test();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean connected = false;
private BluetoothSocket sock;
private InputStream in;
private OutputStream out;
private Button button1;
private Button button2;
private Button button3;
private TextView data_t;
private BufferedReader in_read;
public void test() throws Exception {
if (connected) {
return;
}
new bluetooth_access().execute("");
}
#Override
public void onClick(View v){
// TODO Auto-generated method stub
if(v.equals(button1)){
String s = "turn left";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(v.equals(button2)){
String s = "turn right";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//new post_data().execute("");
}
if(v.equals(button3)){
String s = "read ADC";
byte[] bytes=s.getBytes();
try {
out.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class bluetooth_access extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
BluetoothDevice Pi = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("00:15:83:0C:BF:EB");
Method m=null;
try {
m = Pi.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sock = (BluetoothSocket)m.invoke(Pi, Integer.valueOf(1));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sock.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("PiTest", "++++ Connected");
return null;
}
#Override
protected void onPostExecute(String result) {
;
TextView text = (TextView) findViewById(R.id.textView5);
text.setText("Connected through Bluetooth");
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
// original
try {
in = sock.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out=sock.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
You are trying to write to a socket stream from your main UI thread (from onClick), i would consider doing all socket communication from asynctask itself, or another thread if needed.
your connected variable is not being set, not sure if that was intentional, it can cause multiple execution of your bluetooth asynctask.
I follow one manual to upload images from Android to FTP. If I try to update a photo that have taken I can't see anything on the FTP file. It creates and the size is ok, but contains nothing. Then i try to upload one little image and this is the result:
(Random image to upload)
(Image uploaded)
The code: `class Sender extends AsyncTask
{
File photo;
public Sender(File photo){
this.photo=photo;
}
protected String doInBackground(String... params)
{
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("ftp.fercode.com"));
ftpClient.login(xxx","xxx");
Boolean result = ftpClient.changeWorkingDirectory("/img");
Log.e("existeix carpeta?",result.toString() );
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream srcFileStream=null;
try {
srcFileStream = new FileInputStream(photo.getAbsolutePath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//ftpClient.stor(photo.getAbsolutePath());
boolean status = ftpClient.storeFile("/img/imagePrueba.jpeg",
srcFileStream);
Log.e("Status", String.valueOf(status));
srcFileStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}`
What I'm doing wrong? Thx a lot
That happens because I upload the image like ASCII and not binary. It's just a configuration parameter:
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
I am sending image using Socket Server and Client. It gived me dialog "App not responding" i think beacuse converting this bitmap was making in UiThread. So i tried to change it but i am still getting this message "App is not responding". It's happening when i am sending big imaes +500kb.
Here is my code for Server:
public class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
count++;
// Here where i am doing my code i think is not doing in UiThread..
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
// Firstly i was doing my code here...
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code for client:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try
{
//I am sending my image here...
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
}
So please help my . Why still i am getting not responding dialog?
The ANR error code happens when you block the UI thread more than 5 seconds. If you need to do background work don't use the main thread. Receive the data in a separate thread and post only the result to the UI thread.
I try to create a client server socket beetwen my droid(client) and my PC(server), when i am in local(over wifi) it work perfectely, but when il try over 3G i get this exception when the server try to get clientsocket.getOutputStream()
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
What's the probleme, do eny one know the solution of this?
help please :-(
The Server
public class Server {
ServerSocket serverSocket;
public LinkedBlockingQueue<CDRecCourseDisplay> recCours;
public LinkedList<ClientMail> clientMails;
static Server server;
public static Server getInstance(){
if(server == null){
server = new Server();
}
return server;
}
Server() {
// TODO Auto-generated constructor stub
try {
serverSocket = new ServerSocket(54444);
recCours = new LinkedBlockingQueue<CDRecCourseDisplay>(10);
clientMails = new LinkedList<ClientMail>();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.start();
}
private void start(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true){
try {
Socket socket = serverSocket.accept();
new Thread(new Client(socket)).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public Client(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
if(socket == null) return;
try {
InputStream i = socket.getInputStream();
OutputStream o = socket.getOutputStream();
in = new DataInputStream(i);
out = new DataOutputStream(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test Message");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
Log.d("MESSAGE", buf);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
}
and the client
class Client implements Runnable{
Socket socket;
DataInputStream in;
DataOutputStream out;
public void run() {
// TODO Auto-generated method stub
boolean conected = false;
while(!conected){
try {
Thread.sleep(500);
socket = new Socket("213.233.216.25", 54444);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
conected = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ERROR :", e.getMessage());
}
}
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
String buf = in.readUTF();
log.d("MESSAGE", buf);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while(true){
try {
out.writeUTF("Test message from the phone");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
}
Most networks (Wifi and 3G) use NAT. NAT allows outbound connections, but prevents inbound (internet to device) connections.
When your server and device are both on the same network, as in your case, then this works as you are not traversing NAT gateway.
Rationale: what you are trying to do (connecting from internet to device) will not work in most networks.
I need to send serialized Data from an Android Device to a Java Server.
I don't know why, but the communication seems to be very unstable. In the Debugger, the java.io.StreamCorruptedException: is thrown immediately after the start. not one Object is passing.
Without the debugger, nearly 10 Messages are passed until the same Exception is thrown.
Anyone got an idea, please help me:)
Thank you!
Fabian
Exception:
java.io.StreamCorruptedException: invalid type code: 2F
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at androidAnbindung.AndroidVerwalter.run(AndroidVerwalter.java:114)
java-code:
public void Nachrichtenaustausch(){
port ++;
try {
serverSocket = new java.net.ServerSocket(port);
System.out.println("Warte auf 2. Verbindungsaufbau...");
client = serverSocket.accept();
System.out.println("Verbindung 2 ist eingegangen...");
in = new ObjectInputStream(new ObjectInputStream(client.getInputStream()));
Nachricht n;
// starte den regulären Verkehr mit dem Androidgerät
new Thread(this).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Nachricht speicher;
while (true) {
try {
speicher = (Nachricht) in.readObject();
if (speicher != null) {
System.out.println(speicher.getName()+"..............................."+speicher.getWerte().get(0));
}synchronized (objekliste) {
for (AndroidObject ao : this.objekliste) {
if (speicher.getName().equals(ao.name)) {
ao.abstrakter_Wert = speicher.getAktuellerWert();
if (speicher.getWerte()!=null) {
ao.werte = speicher.getWerte();
}
}
}
}
Thread.sleep(50);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
}
}
}
and the android thread:
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if (!nachrichtenliste.isEmpty()) {
Nachricht speicher = nachrichtenliste.get(0);
try {
out.writeObject(speicher);
out.flush();
synchronized (nachrichtenliste) {
nachrichtenliste.remove(speicher);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thread.sleep(50);
handler.post(this);
}
} catch (Exception e) {
// TODO: handle exception
}
}
I can imagine that Android and Java are not exactly serialization compatible here. So that one side sends a code that the other does not expect.
I'd rather go with some more textual protocol (json, xml) here, than with serialization.