Connecting arduino to android using wifi Shield - android

I am trying to connect arduino Uno to android device using Wifi over a Common Lan connection but the following code is not giving me any response from Arduino. Arduino is working well with the desktop checking code.Here is my android part of the code on click of a toggle button
//WIFI socket code
ToggleButton toggle = (ToggleButton) findViewById(R.id.wifiTButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// wifi thread code
final Runnable r = new Runnable()
{
public void run()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
textOut = (TextView) findViewById(R.id.textOut);
textIn=(EditText) findViewById(R.id.textIn);
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111111);
//dataOutputStream.writeUTF("111111".toString() );//textOut.getText().toString());
textIn.setText(dataInputStream.readByte());
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
});

I was able to solve the problem. It is running well with the command button instead of a toggle button and properly using the thread syntax.
Here is a sample application mainActivity code.
package com.example.arduinoandroid;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Handler handler;
String TAG = "main Activity";
Button bt1;
TextView textOut;
EditText editIn;
static byte abc;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
class Task implements Runnable {
#Override
public void run() {
try {
socket = new Socket("10.0.0.101", 7);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeByte(111);
// dataOutputStream.writeUTF("111111".toString()
// );//textOut.getText().toString());
abc = dataInputStream.readByte();
Toast.makeText(getBaseContext(), abc, Toast.LENGTH_SHORT)
.show();
// textIn.setText(dataInputStream.readUTF());
Log.d(TAG, " why is not working");
} catch (UnknownHostException e) {
Log.d(TAG, "Unknown Host");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "Input Output Exception");
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textOut.setText("working ae");
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
// WIFI socket code
bt1 = (Button) findViewById(R.id.chkButton1);
textOut = (TextView) findViewById(R.id.textOut);
editIn = (EditText) findViewById(R.id.editIn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Task()).start();
}
});
}
}
and the code for xml part is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/chkButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="140dp"
android:text="Check wifi" />
<TextView
android:id="#+id/textOut"
android:layout_width="wrap_content"
android:layout_height="39dp"
android:layout_gravity="bottom|right"
android:text="Output" />
<EditText
android:id="#+id/editIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:text="111111"/>
</LinearLayout>
Please include the following permissions in the manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Related

Send data to bluetooth printer

I am using SimpleBluetoothLibrary to access my bluetooth printer.now i can search available devices,select bluetooth printer from the list,connect to the printer.those parts are done.but i don't know how to send data to the printer for print job.this is onDeviceConnected method.i've got device address from it.but i want to send data to printer.
#Override
public void onDeviceConnected(BluetoothDevice device) {
//a device is connected so you can now send stuff to it
mTxt.setText("Connection Status:Connected:" + device.getAddress());
Log.d("Mac_Address", device.getAddress());
}
There is a simple example for sending data from Bluetooth.I hope it helps you.
MainActivity.java
package com.example.bluetoothprinter;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// This will find a bluetooth printer device
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// MP300 is the name of the bluetooth printer device
if (device.getName().equals("MP300")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth printer device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// After opening a connection to bluetooth printer device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Close the connection to bluetooth printer.
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
<EditText
android:id="#+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/label"
android:background="#android:drawable/editbox_background" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/entry"
android:layout_marginLeft="10dip"
android:text="Open" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/open"
android:layout_toLeftOf="#id/open"
android:text="Send" />
<Button
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/send"
android:layout_toLeftOf="#id/send"
android:text="Close" />
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothprinter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Result pictures are below:

Android App to print from a bluetooth printer

The app I have found online works flawlessly except when clicking onto the Send Button, after typing something into the textbox, the printer runs, and stops in the middle of the process of printing, program doesn't crash however. I'm just curious if I'm using the wrong UUID, in fact I don't even know what it is. I have this following class, which is the only class needed to run the app, the rest are XML, with all three bluetooth permissions;
package com.example.bluetoothprinter;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity {
// will show the statuses
TextView myLabel;
// will enable user to enter any text to be printed
EditText myTextbox;
// android built in classes for bluetooth operations
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// we are goin to have three buttons for specific functions
Button openButton = (Button) findViewById(R.id.open);
Button sendButton = (Button) findViewById(R.id.send);
Button closeButton = (Button) findViewById(R.id.close);
myLabel = (TextView) findViewById(R.id.label);
myTextbox = (EditText) findViewById(R.id.entry);
// open bluetooth connection
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
// close bluetooth connection
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
} catch (IOException ex) {
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will find a bluetooth printer device
*/
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// OJL411MY29I911JH is the name of the bluetooth printer device shown after scan
if (device.getName().equals("OJL411MY29I911JH")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Tries to open a connection to the bluetooth printer device
*/
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* After opening a connection to bluetooth printer device,
* we have to listen and check if a data were sent to be printed.
*/
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth printer
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Close the connection to bluetooth printer.
*/
void closeBT() throws IOException {
try {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I added code to run closeBT function at the end of the sendData function. if you don't close the connection, I think it is hanging in the process of sending.
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

Connection Time out when connecting to server from android device

I am trying to connect from my android phone to my server. But I got time-out connection error.
what can be the the cause?
my code is
public void onClick(View view) {
if (view == loginBtn) {
if (username.getText().length() != 0 & password.getText().length() != 0) {
progressDialog = ProgressDialog.show(this,Farsi.Convert(""),"Verifying user credential");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Connection connection = getConnection();
User user = connection.login(username.getText().toString(), password.getText().toString());
if (user != null) {
BaseKaizenActivity.getStorageManager().setUser(user);
Log.d("---", user.getId() + " : " + user.getName());
showActivity(MainMenuActivity.class);
}
else {
handleException("Invalid username or password");
}
}
catch (Exception exc) {
handleException(exc.getMessage());
}
finally {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
});
thread.start();
}
else {
handleException("Insert username and password");
}
}
}
The exception I got is
Connect to /10.0.2.2:8080 timed out
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8080 timed out
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(
DefaultClientConnectionOperator.java:156)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.pda.kaizen.ConnectionImpl.executeHttpPost(ConnectionImpl.java:133)
at com.pda.kaizen.ConnectionImpl.login(ConnectionImpl.java:88)
at com.pda.kaizen.activity.LoginActivity$1.run(LoginActivity.java:98)
at java.lang.Thread.run(Thread.java:1019)
Try this sample code:
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
and your xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<EditText
android:id="#+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send"
/>
<TextView
android:id="#+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
firts add this per mission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>

Android TCP Smartphone to PC with USB no wifi

Hi I have managed some code but its not working
I want to control send message from PC To Android over my application via USB not by WIFI
i tried this code
But it's giving me error that
07-13 20:08:28.530: W/System.err(8990): java.net.ConnectException: localhost/127.0.0.1:383 - Connection refused
I have done port forward by adb
For Desktop
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class comunicate {
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(383);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
For Mobile
package demo.app.org;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DemoAppActivity extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("localhost", 383);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}
Isn't this code for tcp communication over wifi? I think you can not communicate with android over USB except for logcat.

Unable to read input from a bluetoothsocket

I've finally managed to connect from my android phone to my device, put I have a problem when I try to read from my bluetooth socket.
So here is my code for establishing connecting to my device, its a class that extends AsyncTask
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class Connect extends AsyncTask<String, Void, String> {
private final static String TAG = "+++CONNECT THREAD+++";
ProgressDialog progressDialog;
Context context;
BluetoothSocket tmp;
BluetoothDevice device;
BluetoothAdapter ba;
Button connect;
int bt_port_to_connect;
ReadInput ri;
InputStream is;
byte[] test;
public Connect(Context context, BluetoothDevice device, BluetoothAdapter ba, Button connect) {
this.ba = ba;
this.context = context;
this.device = device;
this.connect = connect;
bt_port_to_connect = 9;
}
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Connecting to device",false);
}
#Override
protected String doInBackground(String... arg0) {
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, bt_port_to_connect);
} 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 {
ba.cancelDiscovery();
tmp.connect();
ri = new ReadInput(tmp);
ri.start();
} catch (IOException e) {
Log.e("+++CONNECT1+++","EXCEPTION: " + e.getMessage());
try {
tmp.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + " insecure socket type" +
" socket during connection failure", e2);
}
Log.e("+++CONNECT2+++", e.getLocalizedMessage());
}
boolean isConnected = tmp.isConnected();
if(isConnected) {
return "connected";
}
else {
return "notConnected";
}
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
if(result.equals("connected")) {
connect.setEnabled(false);
Toast.makeText(context, "Connected to device: "+device.getName().toString(), Toast.LENGTH_LONG).show();
//new ReadIn(context, tmp).execute("");
}
else if(result.equals("notConnected")) {
Toast.makeText(context, "Can`t reach host", Toast.LENGTH_LONG).show();
}
}
}
As you can see, the line below tmp.connect(); I create a new object of a new class, this is the class which I want to handle the reading of the inputStream So here is the code for that class:
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ReadInput extends Thread {
BluetoothSocket socket;
private InputStream is;
public ReadInput(BluetoothSocket socket) {
Log.i("READINPUT", "INSIDE READ INPUT THREAD CONSTRUCTOR!!!");
InputStream tmpIn = null;
this.socket = socket;
is = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e("READINPUT", "Temp socket in created: " + e.getMessage());
}
is = tmpIn;
}
public void run() {
Log.i("READINPUT", "INSIDE READ INPUT THREAD RUN METHOD!!!");
byte[] buffer = new byte[1024];
int bytes = 0;
while(true) {
try {
bytes = is.read(buffer);
} catch (IOException e) {
Log.e("FROM RUN METHOD: ", e.getMessage());
}
Log.i("INPUTSTREAM GOT: ", Integer.toString(bytes));
}
}
}
I have two Log.i methods in my last code, this outputs the correct info to LogCat stating where in the code I am. But it doesnt output the content of the stream to LogCat. What am I doing wrong here? Yes, I've looked into the BluetoothChat example.
Thanks in advance!
EDIT 1
I've done some research in the constructor of the ReadInput Class.
is = tmpIn;
try {
Log.i("InputStream: ", Integer.toString(is.available()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This snippet will only output to logcat that is returns 0 which means that the InputStream is not available. Any suggestions?
I found using a buffered reader works well with a blietooth device. And then I just used a while.loop with br.isReady in a while true listener. Basically makes a "listener"

Categories

Resources