In My project Need to print Pdf file Via Bluetooth Printer. I write a code to print via pdf
Its for fine for a Text,
But I want to Print PDF file on Bluetooth printer.
My java Code to Print Text
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
// listdata(lv);
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);
Button btnco= (Button) findViewById(R.id.btnconnect);
btnco.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
findBT();
openBT();
} catch (Exception ex) {
}
}
});
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) {
startActivity(new Intent(MainActivity.this,NewAct.class));
}
});
// 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");
Toast.makeText(MainActivity.this, "No bluetooth available", Toast.LENGTH_LONG).show();
// startActivity(new Intent(MainActivity.this,NewAct.class));
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
Toast.makeText(this, "OPen", Toast.LENGTH_LONG).show();
//startActivity(new Intent(MainActivity.this,NewAct.class));
}
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(NewAct.printer)) {
//openBT();
mmDevice = device;
break;
}
else {
}
}
}
{
myLabel.setText("Bluetooth Device Found");
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 (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();
}
}
public void listdata(ListView lv){
try{
pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> list = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
#SuppressWarnings("unchecked")
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}catch(Exception e)
{
Toast.makeText(this, "error"+e, Toast.LENGTH_LONG).show();
}
}
I don't have Idea How to Pass Pdf file for print to Bluetooth Printer
Please Help Me How i can do this
Thanks In Advance.
You could try getting bytes from a pdf file & send them to printer as follows:
/*
* 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";
InputStream is = this.openFileInput("filename.pdf"); // Where this is Activity
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
byte[] printformat = { 27, 33, 0 }; //try adding this print format
mmOutputStream.write(printformat);
mmOutputStream.write(bytes);
// tell the user data were sent
myLabel.setText("Data Sent");
closeBT();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
You will need to add following permissions in your Android Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Any application print a pdf has some library to decode pdf.
Of course you can send only a text to your printer.
If you want to print directly pdf you need your own library to do that.
For android i always use mupdf, very powerfuf lib and open source.
look at stackoverflow how to install step-by-step Integrate MuPDF Reader in an app
after you done run a full demo project from https://github.com/derek-watson/mupdf
list on directory (mupdf/platform/android/)
It will run main activity ChoosePDFActivity.java after you picked up pdf from your device it will showing, then main top bar have print button (PrintDialogActivity.java to print on google cloud print) change code here to send stream to your printer
Hope this help!!!
Most bluetooth printers do not support printing PDFs out of the box.
What you need to do is use the Android printer framework or any other library/class like PDFRenderer to convert the PDF pages to images and send those images to the printer with an emulation the printer understands (ex ZPL, CPCL, PCL-3 etc.)
You could try to open the pdf using an Android intent if it's possible to print it from another app (maybe the manufacturer's own?)
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
c.startActivity(intent);
You can make the app first convert PDF into a Bitmap, silently, then print the Bitmap via the thermal printer.
Related
I have looked all over for a solution to this problem, I have not come up with a solution that works.
Currently, I send and receive packets on my android device emulator using my loopback/localHost address. This proccess works successfuly, however when I try running the same code using my computer's public address the server never receives the packets.
private String hostName = "99.248.222.229";
//private String hostName = "10.0.2.2";
private InetAddress hostAddress;
#Override
protected void onCreate(Bundle savedInstanceState)
{
CreateAddress addressGetter = new CreateAddress();
try {
hostAddress = addressGetter.execute(hostName).get();
} catch(Exception e){
e.printStackTrace();
}
Button btnLock = (Button) findViewById(R.id.btnLock);
btnLock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendReceiveTask = new runUdpClient();
byte[] udpMsg = {(byte)housenumber, (byte)doornumber, LK_MSG, UNLOCK};
System.out.println(hostAddress);
sendPacket = new DatagramPacket(udpMsg, udpMsg.length, hostAddress, portnumber);
DatagramPacket receivePacket = null;
try {
receivePacket = sendReceiveTask.execute(sendPacket).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
currentDoorState = (receivePacket.getData()[3]==UNLOCK);
updateDoorStatus(currentDoorState);
int doorNum = doornumber;
eventArrayList.add(0, (getCurrentTimeStamp() + eventString.replace("doornum", Integer.toString(doorNum)))+ ((currentDoorState) ? "unlocked." : "locked."));
adapter.notifyDataSetChanged();
}
});
}
private class runUdpClient extends AsyncTask<DatagramPacket, Void, DatagramPacket>{
#Override
protected DatagramPacket doInBackground(DatagramPacket ...params){
DatagramSocket ds = null;
//SEND
try {
ds = new DatagramSocket();
DatagramPacket dp;
//dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), hostAddress, portnumber);
dp = params[0];
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//RECEIVE
DatagramPacket incomingPacket = new DatagramPacket(new byte[100], 100);
try {
ds.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
try {
ds.receive(incomingPacket);
} catch (IOException e){
e.printStackTrace();
}finally{
if(ds != null) ds.close();
}
System.out.println("Packet recieved from server" + Arrays.toString(incomingPacket.getData()));
return incomingPacket;
}
}
This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 8 years ago.
I don't know why this error keeps popping up. Here is my entire class;
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("Star Micronics")) {
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();
}
}
/*
* 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();
}
}
/*
* 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");
closeBT();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}//End of class
This code snippet is a one class application, which is supposed to print whatever is written into the text field but when I check for paired devices, it gives the error of the title.
Any suggestions why??
This error will mainly arise if you do a heavy network operation over main thread. I mean without using any asynctask or handler in your class you are doing the network operations.
SO use as much handler or asynctask when you are going to make a network call in your application to download, to post something from your device to server etc.
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();
}
}
i want to send a udp packet from my laptop to an android device, i write a simple App for that but it doesn't work, i think that the port(5554) that i have been used is the problem.
Code:
`private void runUdpServer()
EditText RecieveText = (EditText) findViewById(R.id.editText1);
EditText check = (EditText) findViewById(R.id.editText2);
String lText;
byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
RecieveText.setText("try1");
try {
RecieveText.setText("try2");
ds = new DatagramSocket(UDP_SERVER_PORT); // i think the problem is here
//disable timeout for testing
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
RecieveText.setText("try");
ds.receive(dp);
lText = new String(lMsg, 0, dp.getLength());
Log.i("UDP packet received", lText);
RecieveText.setText(lText);
check.setText("port opened");
} catch (SocketException e) {``
check.setText("SocketException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
check.setText("port didn't open");
} finally {
if (ds != null) {
ds.close();
RecieveText.setText("not connected1");
}
else {RecieveText.setText("not connected1");}
}
check.setText("end");
if (ds != null){RecieveText.setText("connected");}
else {RecieveText.setText("not connected");}
}
}
I dont think it is a port issue... print your error log to have a better idea of faillure.... any way try this ... not checked for any typo.... Also keep in mind that any networking task is better to be inside an async task...
int port =1855; ///any port that you want > 1024
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1616;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.1.1"); ////SERVER IP ADDRESS
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
///SENDING
byte[] send= new byte[60*1024];
DatagramPacket send_packet = new DatagramPacket(send, send.length);
try {
socket.send(send_packet);
} catch (IOException e) {
e.printStackTrace();
}
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
///Do something whit recv_packet
}
I use the following code to receive the data from a particular port. It's not working in Android. But sending data to particular port is working fine.
public class UDPDemo extends Activity {
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.recv_message);
try {
DatagramSocket clientsocket=new DatagramSocket(9876);
byte[] receivedata = new byte[1024];
while(true)
{
DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
Log.d("UDP", "S: Receiving...");
clientsocket.receive(recv_packet);
String rec_str = new String(recv_packet.getData());
tv.setText(rec_str);
Log.d(" Received String ",rec_str);
InetAddress ipaddress = recv_packet.getAddress();
int port = recv_packet.getPort();
Log.d("IPAddress : ",ipaddress.toString());
Log.d(" Port : ",Integer.toString(port));
}
} catch (Exception e) {
Log.e("UDP", "S: Error", e);
}
}
}
If you are using the emulator you may need setup redirects, remember the emulator is behind a virtual router.
In other words, type these commands in;
telnet localhost 5554
redir add udp:9876:9876
and try again.
Used Port numbers
Create Datagram packet
try {
mDataGramSocket = new DatagramSocket(Config.PORT_NUMBER);
mDataGramSocket.setReuseAddress(true);
mDataGramSocket.setSoTimeout(1000);
} catch (SocketException e) {
e.printStackTrace();
}
Call below function through AsyncTask
Create Function to receive infinitely
public void receive() {
String text;
byte[] message = new byte[1500];
DatagramPacket p = new DatagramPacket(message, message.length);
try {
while (true) { // && counter < 100 TODO
// send to server omitted
try {
mDataGramSocket.receive(p);
text = new String(message, 0, p.getLength());
// If you're not using an infinite loop:
//mDataGramSocket.close();
} catch (SocketTimeoutException | NullPointerException e) {
// no response received after 1 second. continue sending
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
// return "error:" + e.getMessage();
mReceiveTask.publish("error:" + e.getMessage());
}
// return "out";
}