Print in Android using a printer with IP address and Port number - printing

My query is I have a printer connected to the Wifi and I am able to connect to that printer using the IP address of the printer but I am not able to print from that printer.
MY code:-
class MakeConnection extends AsyncTask<String, Void, String>{
String check = "NO";
#Override
protected String doInBackground(String... params) {
Socket sock = null;
PrintWriter oStream = null;
try
{
sock = new Socket(ipAddress, 9100);
oStream = new PrintWriter(sock.getOutputStream());
oStream.write("HI,test from Android Device");
check = "yes";
oStream.flush();
}
catch (IOException e)
{
e.printStackTrace();
Logger.LogError(TAG, e.toString());
AppToast.showShortToast(mContext, e.toString());
}
finally {
oStream.close();
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
Logger.LogError(TAG, check);
super.onPostExecute(s);
}
}
where I am wrong?

Related

MQTT subscribe not working in Android

I am trying to get a message from the MQTT Broker using the Android service, but it does not work.
The library used is the Paho MQTT library, and the source code is as follows.
final MqttConnectOptions hIoTConnectionOptions = new MqttConnectOptions();
hIoTConnectionOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
hIoTConnectionOptions.setAutomaticReconnect(true);
hIoTConnectionOptions.setCleanSession(false);`
try {
hIoTAndroid = new MqttClient(ip_addr, clientID, new MemoryPersistence());
IMqttToken conToken = hIoTAndroid.connectWithResult(hIoTConnectionOptions);
hIoTAndroid.setCallback(MqttMessagingService.this);
conToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
hIoTAndroid.setCallback(MqttMessagingService.this);
try {
IMqttToken subToken = hIoTAndroid.subscribeWithResponse(subtopic, 1);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG, "Successfully subscribe to: " + subtopic);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Couldn't subscribe to: " + subtopic);
}
});
} catch (MqttException | NullPointerException ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "Failed Connection");
}
});
} catch (MqttException ex) {
Log.d(getClass().getCanonicalName(), "Connection attempt failed with reason code = " + ex.getReasonCode() + ":" + ex.getCause());
}
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d(TAG, "Connection is established....");
}
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "The Connection was lost,,");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG, new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG, "Sent Message !");
}
The publish and deliveryComplete functions work fine, but the subscribe function and messagArrived do not work. Why?

Check SerialPort Exist Modem?

In C# 2005, I used the Nokia E63, I want to check SerialPort Exist Modem, While it run does not get run COM port, you see my code
private void btnGetPort_Click(object sender, EventArgs e)
{
cmbPort.Items.Clear();
foreach (string portName in SerialPort.GetPortNames())
{
try
{
using (SerialPort sp = new SerialPort(portName, 9600))
{
if (!(sp.IsOpen)) sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
sp.Write("AT\r\n");
System.Threading.Thread.Sleep(100);
string response = sp.ReadExisting();
if (response == "OK")
{
cmbPort.Items.Add(portName);
}
}
}
catch (Exception ex)
{
continue;
}
}
}

Blackberry Push Integration Client Sample Code

I need a sample application code for push integration in my blackberry application. I have registered my application for the push credentials and have received them.
please help,
Kind Regards,
Rupesh
This is fully working push application code it may be help you for implement push notification.
public class push_Main {
/**
* Entry point for this application
* #param args Command line arguments (not used)
*/
private static final String REGISTER_SUCCESSFUL = "rc=200";
private static final String DEREGISTER_SUCCESSFUL = REGISTER_SUCCESSFUL;
private static final String USER_ALREADY_SUBSCRIBED = "rc=10003";
private static final String ALREADY_UNSUSCRIBED_BY_USER = "rc=10004";
private static final String ALREADY_UNSUSCRIBED_BY_PROVIDER = "rc=10005";
private static final String PUSH_PORT = ""; //push port
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = ""; // add application id
// private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=seekrit string";
private static String URL = "http://:100"; // PORT 100 add your posh port.
private static final int CHUNK_SIZE = 256;
public static ListeningThread _listeningThread;
public static StreamConnectionNotifier _notify;
private static final long ID = 0x954a603c0dee81e0L;
public push_Main() {
// TODO Auto-generated constructor stub
NotificationsManager.registerSource(ID, theSource, NotificationsConstants.IMPORTANT);
if(_listeningThread==null)
{
System.out.println("msg on listening thread 1");
_listeningThread = new ListeningThread();
System.out.println("msg on listening thread 2");
_listeningThread.start();
System.out.println("msg on listhning thread 3 ");
}
}
public static class ListeningThread extends Thread
{
private boolean _stop = false;
/**
* Stops the thread from listening.
*/
private synchronized void stop()
{
_stop = true;
try
{
// Close the connection so the thread will return.
_notify.close();
}
catch (Exception e)
{
}
}
/**
* Listen for data from the HTTP url. After the data has been read,
* render the data onto the screen.
* #see java.lang.Runnable#run()
*/
public void run()
{
StreamConnection stream = null;
InputStream input = null;
MDSPushInputStream pushInputStream=null;
while (!_stop)
{
try
{
// Synchronize here so that we don't end up creating a connection that is never closed.
synchronized(this)
{
// Open the connection once (or re-open after an IOException), so we don't end up
// in a race condition, where a push is lost if it comes in before the connection
// is open again. We open the url with a parameter that indicates that we should
// always use MDS when attempting to connect.
System.out.println("\n\n msg connection 1");
_notify = (StreamConnectionNotifier)Connector.open(URL);
System.out.println("\n\n msg connection 2");
}
while (!_stop)
{
// NOTE: the following will block until data is received.
System.out.println("\n\n msg notify 1");
stream = _notify.acceptAndOpen();
System.out.println("\n\n msg 1 ");
try
{
System.out.println("\n\n msg 2");
input = stream.openInputStream();
System.out.println("\n\n msg 3 ");
pushInputStream= new MDSPushInputStream((HttpServerConnection)stream, input);
System.out.println("\n\n msg 4");
// Extract the data from the input stream.
DataBuffer db = new DataBuffer();
byte[] data = new byte[CHUNK_SIZE];
int chunk = 0;
while ( -1 != (chunk = input.read(data)) )
{
db.write(data, 0, chunk);
}
updateMessage(data);
// This method is called to accept the push.
pushInputStream.accept();
data = db.getArray();
}
catch (IOException e1)
{
// A problem occurred with the input stream , however, the original
// StreamConnectionNotifier is still valid.
// errorDialog(e1.toString());
}
finally
{
if ( input != null )
{
try
{
input.close();
}
catch (IOException e2)
{
}
}
if ( stream != null )
{
try
{
stream.close();
}
catch (IOException e2)
{
}
}
}
}
}
catch (IOException ioe)
{
// Likely the stream was closed. Catches the exception thrown by
// _notify.acceptAndOpen() when this program exits.
errorDialog(ioe.toString());
}
finally
{
/*
if ( _notify != null )
{
try
{
_notify.close();
_notify = null;
}
catch ( IOException e )
{
}
}
*/
}
}
}
}
private static void updateMessage(final byte[] data)
{
System.out.println("\n\n msg 6");
Application.getApplication().invokeLater(new Runnable()
{
public void run()
{
// Query the user to load the received message.
// Dialog.alert( new String(data));
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run()
{
NotificationsManager.triggerImmediateEvent(ID, 0, null, null);
Dialog d = new Dialog( Dialog.D_OK, new String(data) ,0, null, Screen.DEFAULT_CLOSE);
// _dialogShowing = true;
UiApplication.getUiApplication().pushGlobalScreen( d, 10, UiApplication.GLOBAL_MODAL );
// Dialog is closed at this point, so we cancel the event.
}
} );
}
});
}
public static void registerBpas() {
/**
* As the connection suffix is fixed I just use a Thread to call the connection code
*
**/
new Thread() {
public void run() {
try {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + Conn.getConnectionParameters();
System.out.println("\n\n\n msg registerBPAS URL is: "+ registerUrl);
HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE : " + response);
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + Conn.getConnectionParameters();
System.out.println("\n\n\n\n\n\n msg nextUrl : " + nextUrl);
HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
InputStream nextInputStream = nextHttpConnection.openInputStream();
response = new String(IOUtilities.streamToBytes(nextInputStream));
System.out.println("\n\n\n\n\n\n msg RESPOSE CODE 1: " + response);
close(nextHttpConnection, is, null);
if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
System.out.println("msg Registered successfully for BIS push");
} else {
System.out.println("msg BPAS rejected registration");
}
} catch (final IOException e) {
System.out.println("msg IOException on register() " + e + " " + e.getMessage());
}
}
}.start();
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
public static void errorDialog(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(message);
}
});
}
private static String formRegisterRequest(String bpasUrl, String appId, String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
}

http post blackberry (null response)

I have used this code mod from some url here :
HttpConnection httpConnection = (HttpConnection) Connector.open(webservice_address,Connector.READ_WRITE);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("category", String.valueOf(category));
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
os.close();
return httpConnection.getResponseMessage();
But response is always the same, i obtain a "null all times , when i was expected to have a JSON object response , any idea?
P.S: I'm sure server sends data
P.S: I have tried with Connector.READ_WRITE with the same result.
P.S: I'm doing it in the blackberry 9930 simulator
Try like this sample code:
public class ConnectionThread extends Thread
{
String url;
HttpConnection httpConnection;
InputStream inputStream;
String id="0";
StringBuffer stringBuffer=new StringBuffer();
public ConnectionThread(String url)
{
this.url=url;
}
public void run()
{
try
{
httpConnection=(HttpConnection)Connector.open("Giver Your URL"+";interface=wifi");
URLEncodedPostData oPostData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
oPostData.append("category",id);//Parameters list;
oPostData.append("categoryName","Categ1");
System.out.println("================"+oPostData.toString());
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, oPostData.getContentType());
byte [] postBytes = oPostData.getBytes();
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
OutputStream strmOut = httpConnection.openOutputStream();
strmOut.write(postBytes);
strmOut.flush();
strmOut.close();
int response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
inputStream = httpConnection.openInputStream();
int c;
while((c=inputStream.read())!=-1)
{
stringBuffer.append((char)c);
}
callBack(stringBuffer.toString());
}
else
{
callBack("ERROR");
}
}
catch (Exception e)
{
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
StartUp.exceptionHandling(e.getMessage());
}
}
finally
{
try
{
if(httpConnection!=null)
{
httpConnection.close();
}
if(inputStream!=null)
{
inputStream.close();
}
}
catch (Exception e2)
{}
}
}
private void callBack(String response)
{
if(response.equals("ERROR"))
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
// Put an alert here that "URL Not found";
}
else
{
try
{
System.out.println(response);
//do what you want;
}
catch (Exception e)
{
// Put an alert here that "Data Not found";
}
}
}
}
This is a sample code for POST the data;
Cau u please add Connector.READ_WRITE in Connector.open
HttpConnection httpConnection = (HttpConnection) Connector.open(webservice_address,Connector.READ_WRITE);
Have you tried to avoid calling os.close() before reading the response?

Blackberry - send sms timeout

I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}

Resources