Establishing ServerSocket connection - android

I used this code in my application-
public class BorderCastList extends Activity {
private VideoView video;
private ServerSocket server;
private MediaController media;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Settings window for translucent state
// this.getWindow().setFormat(PixelFormat.TRANSLUCENT);
this.setContentView(R.layout.video);
new Thread(new Runnable() {
#Override
public void run() {
try {
Log.i("test", "before info ServerSocket");
server = new ServerSocket(8050)
Log.i("test", "after info ServerSocket");
Log.i("ip:" + server.getLocalSocketAddress() + "----port: "
+ server.getLocalPort(), "");
Log.i("service ip: " + server.getInetAddress(), "");
Log.i("Server build success************", "");
// Socket socket = server.accept();
} catch (Exception e) {
Log.i("aaa", "bbbb");
e.printStackTrace();
}
}
}).start();
)
Why am I getting the log output Log.i("test", "before info ServerSocket"); but not Log.i("test", "after info ServerSocket");
Log.i("ip:" + server.getLocalSocketAddress() + "----port: "+ server.getLocalPort(), "");
Log.i("server ip: " + server.getInetAddress(), "");
Log.i("Server build success************", "");
Why does it not execute after new ServerSocket(8050)?

On Galaxy Nexus Android 4.1.2 your code creates and binds the socket without problems. Do you have uses-permission android:name="android.permission.INTERNET" in your manifest? Otherwise just expect the stack trace and also bbbb about the aaa.

Related

Logs don't get printed in the logcat

I'm having a weird problem. I already lost a lot of time trying to understand
and solve this but nothing works.
I have an app that communicates with another device across bluetooth connection
to receive some sensor data. In that point, everything works fine, I can connect
to the device, receive and treat the messages.
But yesterday, I decided to create some kind of log file to directly save in the
internal memory the data received from the device without any kind of transformation from my app.
To receive the data from the device, I have a background thread:
public class CommunicationThread extends Thread {
private static final UUID UUID_DEVICE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = CommunicationThread.class.getSimpleName();
private CommunicationListener mListener;
private boolean mRunning;
private BluetoothSocket mBluetoothSocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
public interface CommunicationListener {
void onMessageReceived(String msg);
}
public CommunicationThread(
#NonNull BluetoothDevice device,
#Nullable CommunicationListener listener) throws IOException {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID_DEVICE);
socket.connect();
this.mBluetoothSocket = socket;
this.mInputStream = socket.getInputStream();
this.mOutputStream = socket.getOutputStream();
this.mListener = listener;
}
#Override
public void run() {
mRunning = true;
byte[] bytes = new byte[1024];
int length;
while (mRunning) {
try {
Log.d(TAG, "Waiting for message");
// read the message (block until receive)
length = mInputStream.read(bytes);
String msg = new String(bytes, 0, length);
Log.d(TAG, "Message: " + msg);
// Message received, inform the listener
if (mListener != null)
mListener.onMessageReceived(msg);
} catch (Exception e) {
Log.e(TAG, "Error reading the message", e);
}
}
}
public void sendCommand(String msg) {
try {
mOutputStream.write((msg).getBytes());
} catch (Exception e) {
Log.e(TAG, "Error to send message", e);
}
}
public void stopCommunication() {
mRunning = false;
mListener = null;
try {
if (mBluetoothSocket != null) {
mBluetoothSocket.close();
}
if (mInputStream != null) {
mInputStream.close();
}
if (mOutputStream != null) {
mOutputStream.close();
}
} catch (IOException e) {
Log.e(TAG, "Error to stop communication", e);
}
}
}
This thread works pretty fine and when a message is received, it informs the listener,
my Controller class. The first thing that I try to do when a message comes, is save it:
public class Controller implements CommunicationThread.CommunicationListener
...
#Override
public void onMessageReceived(final String msg) {
Log.d(TAG, "onMessageReceived(msg): " + msg);
mLogCreator.saveThis(msg);
....
}
}
Here is the LogCreator class:
public class LogCreator {
private static final String TAG = LogCreator.class.getSimpleName();
public static final String LOG_FILE_NAME = "log.txt";
private final Context mContext;
private volatile String mTempFullLog;
public LogCreator(Context context) {
mContext = context.getApplicationContext();
File dir = new File(mContext.getFilesDir(), "log_folder");
if (!dir.exists()) {
dir.mkdirs();
File file = new File(dir, LOG_FILE_NAME);
writeString(file, "");
Log.d(TAG, "empty file created");
}
}
public void saveThis(final String data) {
mTempFullLog += "\n" + data;
Log.d(TAG, "New log: " + data);
}
public void start() {
File dir = new File(mContext.getFilesDir(), "log_folder");
File file = new File(dir, LOG_FILE_NAME);
mTempFullLog = readString(file);
Log.d(TAG, "File: " + file);
Log.d(TAG, "Temp full log: " + mTempFullLog);
}
public void stop() {
File dir = new File(mContext.getFilesDir(), "log_folder");
File file = new File(dir, LOG_FILE_NAME);
writeString(file, mTempFullLog);
Log.d(TAG, "log saved: " + mTempFullLog);
}
}
The LogCreator class is already initialized and it works properly, because
if I try to read the file later, everything is there.
The real problem is the following: there is a lot of calls to Log.d during
this execution flow, and this makes very easy to me to understand the all process.
But, the logs are only printed in the logcat until this Log.d call, in the
CommunicationThread class:
Log.d(TAG, "Waiting for message);
After the message received, all code executes normally, but no logs are printed in
the logcat and I really dont know why.
Logs not printed:
CommunicationThread:
Log.d(TAG, "Message: " + msg);
Controller:
Log.d(TAG, "onMessageReceived(msg): " + msg);
LogCreator:
Log.d(TAG, "New log: " + data);
Like I said, I know that everything is working fine with the code because the log
file is created in internal memory even without the logcat prints. It cost me
some hours to realize that the problem is only with the log and not really in
my code.
For testing purpose, if I add this code in the saveThis method of LogCreator,
it executes normally:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, data, Toast.LENGTH_SHORT).show();
}
});
This makes me think that everything could be a thread problem, because the start
and stop methods of LogCreator are both called from the main thread not the CommunicationThread and both methods have their logs printed. Because of this, in the onMessageReceived method
of the Controller class, I tried this:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mLogCreator.saveThis(msg);
}
});
But, unfortunately, the logs don't get printed in the logcat. The toast is still
executed and the data are still saved to the file.
If anyone has any idea of what might be causing this, I really want to know, thanks.
I finally find the solution myself. The reason why the following not work is not clear for me, and IMO it should be treated like a bug.
I compile the app in debug mode and discover that the string received from the device has a "\r" in the end.
Example: "15.50\r"
So, for some strange reason, if I try to do this:
Log.d(TAG, "New log: " + data);
Nothing prints and we don't receive no warnings at all.
But, if I do this instead:
Log.d(TAG, "New log: " + data.replace("\r", ""));
Where data is: "15.50\r"
Everything works and the logcat prints the message.

Error code 503 on transferring file using xmpp

I am trying to send an image file using smack and openfire xmpp. For this I am using FileTransferManager class. To use FileTransferManager class I am using asmack-android-6.jar. I followed this link to do file sharing. This issue is also shared in comments below on this tutorial but no good resolution is given to this issue. Then I searched over stack overflow, Many Developers have asked this question but only 1-2 have got replies that they have accepted, others not.
I studied all the answers that I found, tried all the ways that google gave me but still unable to solve this problem.
The code I used is:
d.findViewById(R.id.btnsendphoto).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!filepath.equals("")) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null) {
sdm = new ServiceDiscoveryManager(
connection);
Log.e("service discovery", "SDM");
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
}
mFileTransferManager = new FileTransferManager(
connection);
/*
* OutgoingFileTransfer transfer =
* mFileTransferManager
* .createOutgoingFileTransfer
* ("98c6d889473a6fae#pc/Smack");
*/
String to = connection.getRoster()
.getPresence("98c6d889473a6fae#pc")
.getFrom();
OutgoingFileTransfer transfer = mFileTransferManager
.createOutgoingFileTransfer(to);
File file = new File(filepath);
try {
//[configureProviderManager](http://paste.ubuntu.com/9932239/)
configureProviderManager(connection);
transfer.sendFile(file, "test_file");
} catch (XMPPException e) {
e.printStackTrace();
}
while(!transfer.isDone()) {
Log.d("status", transfer.getStatus().toString());
Log.d("percent", new Long(transfer.getBytesSent()).toString());
if (transfer.getStatus() == Status.error) {
Log.e("percent", "Error " + new Long(transfer.getBytesSent()).toString() + " " + transfer.getError() + " " + transfer.getException());
transfer.cancel();
}
if(transfer.getStatus().equals(Status.refused))
System.out.println("refused " + transfer.getError());
else if( transfer.getStatus().equals(Status.error))
System.out.println(" error " + transfer.getError());
else if(transfer.getStatus().equals(Status.cancelled))
System.out.println(" cancelled " + transfer.getError());
else
System.out.println("Success");
}
}
d.dismiss();
}
});
The logcat I got is very big, so I gave link of that. So can anyone tell what mistake I am making or can suggest what amendment I make to achieve task
This problem got solved using this link answer don't know why its downvoted. Lemme share answer here also
d.findViewById(R.id.btnsendphoto).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!filepath.equals("")) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager
.getInstanceFor(connection);
if (sdm == null) {
sdm = new ServiceDiscoveryManager(
connection);
Log.e("service discovery", "SDM");
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
}
configureProviderManager(connection);
FileTransferNegotiator.IBB_ONLY = true;
FileTransferNegotiator.setServiceEnabled(connection, true);
mFileTransferManager = new FileTransferManager(
connection);
/*
* OutgoingFileTransfer transfer =
* mFileTransferManager
* .createOutgoingFileTransfer
* ("98c6d889473a6fae#pc/Smack");
*/
String to = connection.getRoster()
.getPresence("98c6d889473a6fae#pc")
.getFrom();
final OutgoingFileTransfer transfer = mFileTransferManager
.createOutgoingFileTransfer(to);
File file = new File(filepath);
try {
configureProviderManager(connection);
transfer.sendFile(file, "test_file");
} catch (XMPPException e) {
e.printStackTrace();
}
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
while (!transfer.isDone()) {
if (transfer.getStatus().equals("Error")) {
Log.d("file transfer",
"ERROR!!! " + transfer.getError());
} else if (transfer.getStatus().equals("Cancelled")
|| transfer.getStatus().equals("Refused")) {
Log.d("file transfer",
"Cancelled!!! " + transfer.getError());
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
};
protected void onPostExecute(Void result) {
if (transfer.getStatus().equals("Refused")
|| transfer.getStatus().equals("Error")
|| transfer.getStatus().equals("Cancelled")) {
Log.i("file transfer", "refused cancelled error "
+ transfer.getError());
} else {
Log.i("file transfer", "Success: " + transfer.getFileName());
}
};
}.execute();
}
d.dismiss();
}
});
I had same problem, I investigated the stanza and solved it this way.
Many people use "/Smack" or "/Resource" as resource part in jid, but it can be configured also the another way.
Resource path is changing with every presence changed of user. Lets say we want to send image to this user:
"user1#mydomain"
You must add "/Resource" part to this jid and it become this:
user1#mydomain/Resource
But /Resource path is changing with presence so you must follow every presence change to update resource path.
Best way is to get user presence is in roster listener and in presencheChanged() method you get last user resource part like this:
Roster roster=getRoster();
roster.addRosterListener(new RosterListener() {
#Override
public void entriesAdded(Collection<Jid> addresses) {
Log.d("entriesAdded", "ug");
context.sendBroadcast(new Intent("ENTRIES_ADDED"));
}
#Override
public void entriesUpdated(Collection<Jid> addresses) {
Log.d("entriesUpdated", "ug");
}
#Override
public void entriesDeleted(Collection<Jid> addresses) {
Log.d("entriesDeleted", "ug");
}
#Override
public void presenceChanged(Presence presence) {
Log.d("presenceChanged", "ug");
//Resource from presence
String resource = presence.getFrom().getResourceOrEmpty().toString();
//Update resource part for user in DB or preferences
//...
}
});
}
Resource string will be some generated string like "6u1613j3kv" and jid will become:
user1#mydomain/6u1613j3kv
That means that you must create your outgoing transfer like this:
EntityFullJid jid = JidCreate.entityFullFrom("user1#mydomain/6u1613j3kv");
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(jid)
transfer.sendFile(new File("DirectoryPath"), "Description");
And that is how i have solved my problem with file transfer on smack and Openfire.
In your case form jid like this:
String to = connection.getRoster().getPresence("98c6d889473a6fae#pc").getFrom();
String Resource = connection.getRoster().getPresence("98c6d889473a6fae#pc").getFrom().getResourceOrEmpty().toString();
OutgoingFileTransfer transfer = mFileTransferManager.createOutgoingFileTransfer(to + "/" + resource);
Also to mention you must add following properties in your Openfire server:
xmpp.proxy.enabled - true
xmpp.proxy.externalip - MY_IP_ADDRESS
xmpp.proxy.port - 7777
Just to mention, I am using Openfire 4.0.2 and Smack 4.2.2.
Also this can be configured the easy way, just set the resource on
XMPPTCPConnectionConfiguration.Builder .
like
XMPPTCPConnectionConfiguration.Builder configurationBuilder =
XMPPTCPConnectionConfiguration.builder();
configurationBuilder.setResource("yourResourceName");

How to clear errors in xmpp chat program in android

Hi I am creating a chat application using xmpp. My problem is that while running the project a dialog box appears showing 'your project contain errors fix then and run', but there is no errors shown in project explorer, a warning is sign is shown(hope it doesn't effect rnuning a project). The console page is showing like this :
[2013-09-25 10:25:01 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/kenai/jbosh/AbstractAttr;
[2013-09-25 10:25:01 - XMPPChatDemo] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/kenai/jbosh/AbstractAttr;
And my program code is :
public class XMPPChatDemoActivity extends Activity {
public static final String HOST = "192.168.1.4";
public static final int PORT = 5222;
public static final String USERNAME = "semyma";
public static final String PASSWORD = "computer";
private XMPPConnection connection;
private ArrayList<String> messages = new ArrayList<String>();
private Handler mHandler = new Handler();
private EditText recipient;
private EditText textMessage;
private ListView listview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recipient = (EditText) this.findViewById(R.id.toET);
textMessage = (EditText) this.findViewById(R.id.chatET);
listview = (ListView) this.findViewById(R.id.listMessages);
setListAdapter();
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.sendBtn);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String to = recipient.getText().toString();
String text = textMessage.getText().toString();
Log.i("XMPPChatDemoActivity", "Sending text " + text + " to " + to);
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
if (connection != null) {
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}
}
});
connect();
}
/**
* Called by Settings dialog when a connection is establised with the XMPP
* server
*
* #param connection
*/
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPChatDemoActivity", "Text Recieved " + message.getBody()
+ " from " + fromName );
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listitem, messages);
listview.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (connection != null)
connection.disconnect();
} catch (Exception e) {
}
}
public void connect() {
final ProgressDialog dialog = ProgressDialog.show(this,
"Connecting...", "Please wait...", false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Create a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(
HOST, PORT);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPChatDemoActivity",
"Connected to " + connection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", ex.toString());
setConnection(null);
}
try {
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(USERNAME, PASSWORD);
Log.i("XMPPChatDemoActivity",
"Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
Log.d("XMPPChatDemoActivity",
"--------------------------------------");
Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
Log.d("XMPPChatDemoActivity",
"User: " + entry.getUser());
Log.d("XMPPChatDemoActivity",
"Name: " + entry.getName());
Log.d("XMPPChatDemoActivity",
"Status: " + entry.getStatus());
Log.d("XMPPChatDemoActivity",
"Type: " + entry.getType());
Presence entryPresence = roster.getPresence(entry
.getUser());
Log.d("XMPPChatDemoActivity", "Presence Status: "
+ entryPresence.getStatus());
Log.d("XMPPChatDemoActivity", "Presence Type: "
+ entryPresence.getType());
Presence.Type type = entryPresence.getType();
if (type == Presence.Type.available)
Log.d("XMPPChatDemoActivity", "Presence AVIALABLE");
Log.d("XMPPChatDemoActivity", "Presence : "
+ entryPresence);
}
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to log in as "
+ USERNAME);
Log.e("XMPPChatDemoActivity", ex.toString());
setConnection(null);
}
dialog.dismiss();
}
});
t.start();
dialog.show();
}
}
Most of the time this happens due to the multiple copies of android-support-v4 libraries in your project and and dependent project.
First try to delete the other android-support-v4 library and make it same for all.
if this works for you then its good other wise follow the below steps thats gonna work with you
1- List item
2-Open Project Build Path,
3-Select "Libraries" tab,
4-Remove all library except the Android Library
5-Adding all required JARs Files
And you are Done.
This error occurs you will better understand by this example - In case you download any project in this project environment means SDK updated in API LEVEL 15 and such type of project you import in your work-space and at this time point to be noted your SDK updated in API LEVEL
19 at this time fixed project setup and it will goes Build Path at this you just add external
libraries android-support-v4 then this problem has occurs due to the multiple copies of android-support-v4/google-play-services if you use Google map libraries in your project.
i hope so you will better understand.
Thankys

How to print image and some data from an android device, using printer (print via bluetooth)?

I am developing one app in which i have to print one receipt, receipt has one logo(static) image view, how can i print this to bluetooth printer? and also i have taken signature by using GestureOverlayView, now i have to print that gesture as well along with logo and some data regarding the receipt.
and i need to print one arabic string as well. which is shown in the TEXT VIEW.
for showing signature i am using image view in my layout. Please check the image,
i am attaching the image which i have to print, please give me some idea about printing it.
i can change the format in printing, means i dont have to print data in rectangles, but image alignment is the main issue, how will i get to know about alignment?
Try using this one....
public class BluetoothPrinterActivity extends Activity {
BluetoothAdapter mBTAdapter;
BluetoothSocket mBTSocket = null;
Dialog dialogProgress;
String BILL, TRANS_ID;
String PRINTER_MAC_ID = "00:1F:B7:02:8F:44";
final String ERROR_MESSAGE = "There has been an error in printing the bill.";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
BILL = "\nSale Slip No: 12345678" + " " + "04-08-2011\n";
BILL = BILL + "----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " " + "17625.0\n";
BILL = BILL + "-----------------------------------------";
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(this, "Device has no bluetooth capability",Toast.LENGTH_LONG).show();
finish();
} else {
if (!mBTAdapter.isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 0);
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
dialogProgress = new Dialog(BluetoothPrinterActivity.this);
dialogProgress.setTitle("Finding printer...");
dialogProgress.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
setResult(RESULT_CANCELED);
finish();
}
});
dialogProgress.show();
}
if (mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
else
mBTAdapter.startDiscovery();
System.out.println("BT Searching status :" + mBTAdapter.isDiscovering());
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("***" + device.getName() + " : "+ device.getAddress());
if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(BluetoothPrinterActivity.this,device.getName() + " Printing data",Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
Toast.makeText(BluetoothPrinterActivity.this,device.getName() + " found", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (dialogProgress != null)
dialogProgress.dismiss();
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void printBillToDevice(final String address) {
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
dialogProgress.setTitle("Connecting...");
dialogProgress.show();
}
});
mBTAdapter.cancelDiscovery();
try {
System.out.println("**************************#****connecting");
BluetoothDevice mdevice = mBTAdapter.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
setResult(RESULT_OK);
finish();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
e.printStackTrace();
setResult(RESULT_CANCELED);
finish();
}
runOnUiThread(new Runnable() {
public void run() {
try {
dialogProgress.dismiss();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
});
}
}).start();
}
}
from this link Bluetooth Printer issue in android
I try my best to give the answer before that you can get the solution from already asked questions
you have 3 options for printing from android app
1>SDKs/Libraries: (like starmicronics, it's limited to few devices)
2>Google Play Apps: (directly calling the intent to thirparty apps)
3>Google cloud print: (recommended. It's easy to use and integrate into an app)
By this we connect any printers like Classic printers, Cloud Print printers.
for using Google print as user perspective user should activate google print service to gmail account, Google cloud print used in many places!
Setting up the google print service:
Blog
https://stackoverflow.com/questions/11323805/how-to-setup-network-printer-to-google-cloud-print/14911180#14911180
Google cloud print set up1
Google cloud print set up2
Printing via gchrome
Google cloud printers
Integrating Cloud printers to App:
In Android there no option for Airprint like other platforms, but Google made awesome cloud printing option for that such that any printer can use the print option from mobile devices.
Sample codes:
funcode
Google cloud print code

aSmack as a service

Basically I have a Main class running the entire project. The code is working perfectly although once the App is unfocused it becomes inactive. I was wondering how I would go about making it a service. One that would startup at boot.
The app will be a one way message system for notifications. I.E.
Desktop Client -> Openfire Server -> Android XMPP Service -> Storage (DB) -> Android GUI for display
As I've said, the Code is working (Connect, Login, Receive) but isn't a service.
I could use the BEEM source but it's too featured and interlaced. I'm after a lightweight service.
The code:
public class MainActivity extends Activity {
public static final String HOST = "fire.example.com";
public static final int PORT = 5222;
public static final String SERVICE = "example.com";
public static final String USERNAME = "metest#fire.example.com";
public static final String PASSWORD = "mepass";
private XMPPConnection connection;
private ArrayList<String> messages = new ArrayList<String>();
private Handler mHandler = new Handler();
private ListView listview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) this.findViewById(R.id.listMessages);
setListAdapter();
connect();
}
/**
* Called by Settings dialog when a connection is establised with
* the XMPP server
*/
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPChatActivity ", " Text Recieved " + message.getBody() + " from " + fromName);
messages.add(message.getBody());
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private void setListAdapter() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, messages);
listview.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
connection.disconnect();
} catch (Exception e) {
}
}
public void connect() {
final ProgressDialog dialog = ProgressDialog.show(this, "Connecting...", "Please wait...", false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Create a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(HOST, PORT, SERVICE);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPChatActivity", "[SettingsDialog] Connected to "+connection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPChatActivity", "[SettingsDialog] Failed to connect to "+ connection.getHost());
Log.e("XMPPChatActivity", ex.toString());
setConnection(null);
}
try {
connection.login(USERNAME, PASSWORD);
Log.i("XMPPChatActivity", "Logged in as" + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
Log.d("XMPPChatActivity", "--------------------------------------");
Log.d("XMPPChatActivity", "RosterEntry " + entry);
Log.d("XMPPChatActivity", "User: " + entry.getUser());
Log.d("XMPPChatActivity", "Name: " + entry.getName());
Log.d("XMPPChatActivity", "Status: " + entry.getStatus());
Log.d("XMPPChatActivity", "Type: " + entry.getType());
Presence entryPresence = roster.getPresence(entry.getUser());
Log.d("XMPPChatActivity", "Presence Status: "+ entryPresence.getStatus());
Log.d("XMPPChatActivity", "Presence Type: " + entryPresence.getType());
Presence.Type type = entryPresence.getType();
if (type == Presence.Type.available)
Log.d("XMPPChatActivity", "Presence AVIALABLE");
Log.d("XMPPChatActivity", "Presence : " + entryPresence);
}
} catch (XMPPException ex) {
Log.e("XMPPChatActivity", "Failed to log in as "+ USERNAME);
Log.e("XMPPChatActivity", ex.toString());
setConnection(null);
}
dialog.dismiss();
}
});
t.start();
dialog.show();
}
}
So basically, How do I make this a service
i guess this example at the given link would give you the idea for making it a service. http://android.codeandmagic.org/small-test-of-asmack-xmpp-client-library/
You need to utilise the Android Service Framework.
You could check out GTalk SMS source as they utilize a service and is open source. (Main Service is the service they use to handle the connection etc. ) though it is also very complicated.
I would highly recommend you check out the basics of utilizing a service in Android.
Remember a service does not create a new thread, everything is still done on the UI thread so if you want to perform long running tasks in the background then you'll also need to implement an asynctask or executor service.
Old question, but I'll put my answer anyways.
You need to create a service, start it and put your code of aSmack connection in the service, not in any activity. The service will retain the connection even when the app is not in foreground. I am using this method in one of my client's app and it's working great.
Also, make sure you use a Handler or AsyncTask in the service to create the socket connection in another non-UI thread. Android will not allow you to create the connection in UI thread anyways.

Categories

Resources