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.
Related
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.
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
I am building an Android app that communicates with an Arduino board via bluetooth, I have the bluetooth code in a class of it's own called BlueComms. To connect to the device I use the following methord:
public boolean connectDevice() {
CheckBt();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
Log.d(TAG, "Connection made.");
return true;
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
return false;
}
Log.d(TAG, "Socket creation failed");
}
return false;
}
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
System.out.println("Bt dsbld");
}
if (mBluetoothAdapter == null) {
System.out.println("Bt null");
}
}
This connects fine but as soon as I leave the activity I connected through it drops the connection, showing this through LogCat,
D/dalvikvm(21623): GC_CONCURRENT freed 103K, 10% free 2776K/3056K, paused 5ms+2ms, total 35ms
I can no longer connect to the device, but if I call killBt() it throws a fatal error and if I try to send data I get a 'Socket creation failed' error. My send message code is as follows:
public void sendData(String data, int recvAct) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
}
}
How should I go about preventing the connection from being paused by the activity I connect with when I switch a different activity, I am switching activities with this code:
Intent myIntent = new Intent(v.getContext(), Timelapse.class);
startActivityForResult(myIntent, 0);
Many Thanks,
Rozz
Where did you store the instance of your BlueComms class? If you put it in the first activity then the class instance would have been killed when that activity was destroyed as you left it and moved to the next activity (NB activities also get destroyed on screen rotation)
So you need to find a way to keep the instance of BlueComms class alive for as long as you need it. You could pass it between activities via public properties and store it in onRetainNonConfigurationInstance() during rotations.
An easier trick is to create a class that extends Application use it as the application delegate for your app and add public property to it to store the instance of BlueComms class within it. That way the instance of BlueComms class would be alive for the lifetime of you app.
Extend Application
import android.app.Application;
public class cBaseApplication extends Application {
public BlueComms myBlueComms;
#Override
public void onCreate()
{
super.onCreate();
myBlueComms = new BlueComms();
}
}
Make your class the application delegate in the app manifest
<application
android:name="your.app.namespace.cBaseApplication"
android:icon="#drawable/icon"
android:label="#string/app_name" >
Access the base app from any of your Activities like this
((cBaseApplication)this.getApplicationContext()).myBlueComms.SomeMethod();
What I have done is, Created a singleton class for BluetoothConnection.
So socket creation happens only for one time.
When onCreate method of any activity is created, it first fetch instance of BluetoothConnection class.
Handler is used to send messages from thread in BluetoothConnection class to the corresponding activity by settings Handler.
Like:
Class MyBTConnection{
private static MyBTConnection connectionObj;
private Handler mHandler;
public MyBTConnection() { //constructor }
public static MyBTConnection getInstance() {
if(connectionObj == null) {
connectionObj = new MyBTConnection();
}
return connectionObj;
}
}
public void setHandler(Handler handler) {
mHandler = handler;
}
..... Code for Bluetooth Connection ....
to send message :
mHandler.obtainMessage(what).sendToTarget();
}
// in first activity
class MainActivity extends Activity {
private MyBTConnection connectionObj;
public onCreate(....) {
/*
* Since this is first call for getInstance. A new object
* of MyBTConnection will be created and a connection to
* remote bluetooth device will be established.
*/
connectionObj = MyBTConnection.getInstance();
connectionObj.setHandler(mHandler);
}
private Handler mHandler = new Handler(){
public void onReceive(...) {
/// handle received messages here
}
};
}
// in second activity
class SecondActivity extends Activity {
private MyBTConnection connectionObj;
public onCreate(....) {
/*
* Since this is second call for getInstance.
* Object for MyBTConnection was already created in previous
* activity. So getInstance will return that previously
* created object and in that object, connection to remote
* bluetooth device is already established so you can
* continue your work here.
*/
connectionObj = MyBTConnection.getInstance();
connectionObj.setHandler(mHandler);
}
private Handler mHandler = new Handler(){
public void onReceive(...) {
/// handle received messages here
}
};
}
I'm currently having exactly the same issue and I was thinking of opening/closing the Bluetooth socket each time an Activity asks for it. Each Activity has it's own BlueComms instance.
Because my application will became a bit complex and there will be Bluetooth threaded requests from different activities, I'm thinking that this way will become very difficult to use and troubleshoot.
Another way I came across by reading here...
https://developer.android.com/guide/components/services.html
A Service can be created on the background having a Bluetooth socket always on. All Bluetooth requests can be made using Intent towards this service. This also creates some fair amount of complexity but feels a lot more tidy and organized.
I'm currently having this dilemma, either to use a thread for each activity or use a service. I don't know which way is actually better.
When you are Selecting A device to connect and when you are click on the device list item for requesting a connection to the device use AsyncTask
and put the connect method inside the AsyncTask like this :-
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
bluetoothSocket.connect();
// After successful connect you can open InputStream
} catch (IOException e) {
e.printStackTrace();
}
**Here is the full code for the same problem that i have cracked :-**
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lablelexconnected.setText("Connecting ...");
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position)
// Toast.makeText(getApplicationContext()," " + bdDevice.getAddress(),Toast.LENGTH_SHORT).show();
Log.i("Log", "The dvice : " + bdDevice.toString());
bdDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
Globals.bluetoothDevice = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
System.out.println("Device in GPS Settings : " + bdDevice);
// startService(new Intent(getApplicationContext(),MyService.class));
/* Intent i = new Intent(GpsSettings.this, MyService.class);
startService(i);*/
// finish();
// connectDevice();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
bluetoothSocket = Globals.bluetoothDevice.createRfcommSocketToServiceRecord(Globals.DEFAULT_SPP_UUID);
bluetoothSocket.connect();
// After successful connect you can open InputStream
InputStream in = null;
in = bluetoothSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
br = new BufferedReader(isr);
while (found == 0) {
String nmeaMessage = br.readLine();
Log.d("NMEA", nmeaMessage);
// parse NMEA messages
sentence = nmeaMessage;
System.out.println("Sentence : " + sentence);
if (sentence.startsWith("$GPRMC")) {
String[] strValues = sentence.split(",");
System.out.println("StrValues : " + strValues[3] + " " + strValues[5] + " " + strValues[8]);
if (strValues[3].equals("") && strValues[5].equals("") && strValues[8].equals("")) {
Toast.makeText(getApplicationContext(), "Location Not Found !!! ", Toast.LENGTH_SHORT).show();
} else {
latitude = Double.parseDouble(strValues[3]);
if (strValues[4].charAt(0) == 'S') {
latitude = -latitude;
}
longitude = Double.parseDouble(strValues[5]);
if (strValues[6].charAt(0) == 'W') {
longitude = -longitude;
}
course = Double.parseDouble(strValues[8]);
// Toast.makeText(getApplicationContext(), "latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course, Toast.LENGTH_SHORT).show();
System.out.println("latitude=" + latitude + " ; longitude=" + longitude + " ; course = " + course);
// found = 1;
NMEAToDecimalConverter(latitude, longitude);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
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.
I found this question: XMPP events on Android, and the answer explains a solution to the problem I am having. But I cannot seem to figure out how to get the packetListener to work. I have tried packetCollectors and packetListeners but noting seems to work.
I am unsure of where I should place the packet listeners. Should it go into the onCreate() method of the service, or in the onStartCommand(), or should it be put into a separate method that runs every few seconds?
My confusion is mostly with the concept of listeners. Is the listener always running, and will trigger as soon as a packet is received? And how do I make sure that the listener can 'see' the packet events coming in?
This is my current attempt at getting this to work:
public class XMPPService extends Service{
private static String TAG = "XMPPService";
XMPPConnection connection;
MultiUserChat muc;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId){
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222);
connection = new XMPPConnection(config);
try
{
connection.connect();
Log.i(TAG,"connected");
}
catch (XMPPException e)
{
Log.e(TAG, "Connection Issue: ", e);
}
try
{
connection.login("user", "password");
muc = new MultiUserChat(connection, "room#conference.jabber.org");
muc.join("nick","password");
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
}
catch (XMPPException e)
{
Log.e(TAG, "Connection Issue: ", e);
}
makeNotification("started");
return 1;
}
private void makeNotification(String msg){
Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MUCTestActivity.class), 2);
notification.setLatestEventInfo(this, "Title", msg, contentIntent);
NotificationManager nmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nmgr.notify(123443, notification);
}
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() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i(TAG, "Got text [" + message.getBody() + "] from [" + fromName + "]");
}
else
{
Log.i(TAG,"null");
}
}
}, filter);
}
}
}
The PacketListener part looks right. It will be attached to smacks connection (the reader thread) and invoked by the connection if a packet, which matches the filter, arrives. You got the concept right.
Returning START_STICKY (please use here the constant and not the value) should also help to keep the service and therefore the connection alive.
Do you see the JID of the connection online? I am not sure if one can always send messages to a JID without being in the roster of the JID. Try enabling debugging in smack: Connection.DEBUG_ENABLED=true. If you have asmack, all debug messages will go into DBMS log. Also the emulator and eclipse with breakpoints are powerful tools to help you analyze the problem.