My Android app is maintaining a socket connection with the server and this connection works fine when the device is connected to Wi-Fi and fails only when the device is connected to the mobile network. Error trace is as follows
org.java_websocket.exceptions.InvalidFrameException: bad rsv 3
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateSingleFrame(Draft_10.java:308)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateFrame(Draft_10.java:285)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:321)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:164)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:185)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at java.lang.Thread.run(Thread.java:841)
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed: bad rsv 3
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed- code: 1002, reason: bad rsv 3
My code is as follows,
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
public class WebSocketService extends Service {
public static final String WEB_SOCKET_SERVICE_RECEIVER = "com.mydomain.myapp.WebSocketServiceReceiver";
public static final String EXTRA_COMMAND = "extraCommand";
public static final String EXTRA_MESSAGE = "extraMessage";
public static final int COMMAND_STOP = -2;
public static final int COMMAND_SEND_MESSAGE = -3;
public static void stopService(Context context, String message) {
Intent intent = new Intent(WEB_SOCKET_SERVICE_RECEIVER);
intent.putExtra(EXTRA_COMMAND, COMMAND_STOP);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("WebSocketService", "onStartCommand");
if (!mStarted) {
mStarted = true;
mWebSocketClosed = false;
mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WebSocketServiceWakeLock");
pingPackets = new Stack<PingPacket>();
registerReceiver(mReceiver, new IntentFilter(
WEB_SOCKET_SERVICE_RECEIVER));
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("WebSocketService", "onDestroy");
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
protected void startWebSocket() throws URISyntaxException {
Log.d("WebSocketServce", "startWebSocket");
String webSocketBaseURL = BuildSpecificConstants.WEB_SOCKET_BASE_URL;
mWebSocketClient = new WebSocketClient(new URI(webSocketBaseURL
+ "?auth_token="
+ SessionManager.getInstance(getApplicationContext())
.getAPIKey())) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("WebSocketServce", "onOpen");
if (!mWakeLock.isHeld()) {
mWakeLock.acquire();
Log.d("WebSocketService", "WakeLock acquired");
}
startPingProtocol();
if (mPendingMessage != null) {
sendMessage(mPendingMessage);
}
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
}
#Override
public void onWebsocketPong(WebSocket conn, Framedata frame) {
super.onWebsocketPong(conn, frame);
try {
if (frame.getOpcode() == Opcode.PONG) {
if (!pingPackets.isEmpty()) {
PingPacket returnedPing = pingPackets.get(0);
if (returnedPing != null) {
returnedPing.consume();
pingPackets.remove(0);
Log.d("WebSocketService", returnedPing.id
+ " pong received");
failedPingCount = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String message) {
try {
JSONObject eventJson = new JSONObject(message);
Log.d("WebSocketService", "Received: " + message);
String eventType = eventJson
.getString(IncomingMessageParams.EVENT);
if (eventType.equals(EventTypes.NEW_BOOKING)) {
Trip trip = Trip
.decodeJSON(
eventJson
.getJSONObject(BookingsResponseParams.KEY_BOOKING),
eventJson.getJSONObject("passenger"),
eventJson.getJSONArray("locations"),
eventJson.optJSONObject("coupon"),
SessionManager
.getInstance(WebSocketService.this));
Intent intent = new Intent(WebSocketService.this,
IncomingBookingActivity.class);
intent.putExtra(IncomingBookingActivity.EXTRA_BOOKING,
trip);
intent.putExtra(
MainActivity.EXTRA_COUNT_DOWN_TIME,
eventJson
.getInt(IncomingMessageParams.LOOKUP_TIME));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SessionManager.getInstance(getApplicationContext())
.setStatus(DriverStatus.BUSY);
LocationUpdateService
.sendStatusChange(WebSocketService.this);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onError(Exception ex) {
ex.printStackTrace();
Log.d("WebSocketService", "Socket closed: " + ex.getMessage());
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
if (!mWebSocketClosed) {
reconnect();
}
}
if (!mWebSocketClosed) {
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
#Override
public void onClose(int code, String reason, boolean remote) {
Log.d("WebSocketService", "Socket closed- code: " + code
+ ", reason: " + reason);
if (code != CloseFrame.NORMAL) {
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(
mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
reconnect();
}
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
};
if (BuildConfig.FLAVOR.equals("production")) {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
SSLSocketFactory factory = sslContext.getSocketFactory();
try {
mWebSocketClient.setSocket(factory.createSocket());
} catch (IOException e) {
e.printStackTrace();
}
}
mWebSocketClient.connect();
}
protected void startPingProtocol() {
pingCounter = 0;
failedPingCount = 0;
pingRunning = true;
if (pingThread == null || !pingThread.isAlive()) {
pingThread = new Thread(new Runnable() {
#Override
public void run() {
while (pingRunning) {
if (failedPingCount < 3) {
PingPacket packet = new PingPacket(pingCounter);
Log.d("WebSocketService", "sending ping "
+ pingCounter);
pingPackets.add(packet);
packet.sendPing(mWebSocketClient);
pingCounter++;
pingCounter %= Byte.MAX_VALUE;
} else {
stopPingProtocol();
Log.d("WebSocketService", "connection lost");
}
try {
Thread.sleep(AppConstants.PING_SPAWN_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
private void stopPingProtocol() {
if (pingThread != null && pingThread.isAlive()) {
pingRunning = false;
pingThread.interrupt();
for (int i = 0; i < pingPackets.size(); i++) {
pingPackets.get(i).consume();
}
pingPackets.clear();
}
}
protected void reconnect() {
if (mConnectionAttempt < AppConstants.MAX_WEB_SOCKET_RECONNECTS) {
mFallbackHandler = new Handler(Looper.getMainLooper());
mFallbackHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacks(this);
mFallbackHandler = null;
}
try {
stopWebSocket();
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
mConnectionAttempt++;
}
}, AppConstants.WEB_SOCKET_BASE_FALLBACK_TIME * mConnectionAttempt);
} else {
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
}
protected void sendMessage(String message) {
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
mWebSocketClient.send(message);
mConnectionAttempt = 1;
Log.d("WebSocketService", "Send: " + message);
} else {
mPendingMessage = message;
}
}
protected void stopWebSocket() {
Log.d("WebSocketService", "Closing");
mWebSocketClosed = true;
mWebSocketClient.close();
stopPingProtocol();
Editor editor = getSharedPreferences(SharedPrefKeys.APP_PREFERENCES,
MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
}
private WakefulBroadcastReceiver mProviderChangedListener = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Helper.checkNetworkStatus(context)) {
mListenForConnectivity = false;
try {
unregisterReceiver(this);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int command = intent.getIntExtra(EXTRA_COMMAND, -1);
switch (command) {
case COMMAND_STOP:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
stopSelf();
break;
case COMMAND_SEND_MESSAGE:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
break;
default:
break;
}
}
};
Private class,
private class PingPacket { protected byte id;
protected Timer timer;
protected PingPacket(byte id) {
this.id = id;
timer = new Timer();
}
protected void sendPing(WebSocketClient client) {
FramedataImpl1 frame = new FramedataImpl1(Opcode.PING);
frame.setFin(true);
client.sendFrame(frame);
Log.d("WebSocketService", id + " ping sent");
timer.schedule(new TimerTask() {
#Override
public void run() {
failedPingCount++;
Log.d("WebSocketService", "Ping " + id + " failed");
}
}, AppConstants.PING_EXPIRE_DELAY);
}
protected void consume() {
timer.cancel();
timer.purge();
}
}
}
What could possibly be causing this?
The InvalidFrameException with a message "bad rsv 3" implies that the protocol exchanged in the WebSocket connection is wrong. Your stack trace implies that Draft_10 is used, but it is too old.
FYI: You can find other WebSocket client libraries for Android in "Which WebSocket library to use in Android app?".
Related
I want to imaplement xmpp connection in my application i refered lot of tutorials in google,but i cnnot get clear idea.
please some one help me out this problem,give suggetion how to implemnt xmpp connection.
thank you.
first You Have to add build.gradle
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
then create LocalBinder class
public class LocalBinder<S> extends Binder {
private final WeakReference<S> mService;
public LocalBinder(final S service) {
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
Then Create service class
public class XmppService extends Service {
public static MyXMPP xmpp;
private String ServiceName = "", HostAddress = "";
private String USERNAME = "";
private String PASSWORD = "";
private SessionManager sessionManager;
#Override
public IBinder onBind(final Intent intent) {
return new LocalBinder<XmppService>(this);
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate() {
sessionManager = new SessionManager(XmppService.this);
ServiceName = Your Service Name ;
HostAddress = Your Host Address;
USERNAME = your xmpp server user name;
PASSWORD = Your xmpp server pwd;
xmpp = MyXMPP.getInstance(XmppService.this, ServiceName, HostAddress, USERNAME, PASSWORD);
xmpp.connect("onCreate");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
MyXMPP.instance=null;
MyXMPP.instanceCreated=false;
xmpp.connection.disconnect();
System.out.println("--------------Xmpp Service Stopped-----------");
}
}
create xmpp class
public class MyXMPP {
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private boolean server_chat_created = false;
private String serviceName = "", hostAddress = "";
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
XmppService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
private static ChatHandler chatHandler;
public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
this.serviceName = mServiceName;
this.hostAddress = mHostAddress;
this.loginUser = loginUser;
this.passwordUser = passwordUser;
this.context = context;
init();
}
public static MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat ,MyServerchat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serviceName);
config.setHost(hostAddress);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,
caller + "=>connecting....",
Toast.LENGTH_LONG).show();*/
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
ReconnectionManager reconnectionManager =
ReconnectionManager.getInstanceFor(connection);
reconnectionManager.setEnabledPerDefault(false);
reconnectionManager.enableAutomaticReconnection();
/*PingManager pingManager =
PingManager.getInstanceFor(connection);
pingManager.setPingInterval(300);*/
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener()
{
#Override
public void onReceiptReceived(final String fromid, final String toid, final String msgid,final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "IOException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();*/
}
});
Log.e("(" + caller + ")",
"SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context,"(" + caller + ")"+ "XMPPException: ",Toast.LENGTH_SHORT).show();*/
}
});
Log.e("connect(" + caller + ")","XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
System.out.println("----login------USERNAME------------" + loginUser);
System.out.println("----login------PASSWORD------------" + passwordUser);
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// connect("");
} catch (Exception e) {
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public int sendMessage(String senderID, String mMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public int sendMessageServer(String senderID, String mMessage) {
if (!server_chat_created) {
MyServerchat =
ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
server_chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
MyServerchat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionCLosed!");
System.out.println("-------------ConnectionCLosed!----------------");
instance = null;
connected = false;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
System.out.println("----------prem Reconnectingin----------------" + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/*Toast.makeText(context, "ReconnectionFailed!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "REConnected!",Toast.LENGTH_SHORT).show();*/
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(mChatManagerListener);
chat_created = false;
server_chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
/*Toast.makeText(context, "Connected!",Toast.LENGTH_SHORT).show();*/
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,final Message message)
{
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"+ message);
if (message.getType() == Message.Type.chat && message.getBody() != null)
{
System.out.println("-----------xmpp message-------------" + message.getBody());
try
{
if (chatHandler == null) {
chatHandler = new ChatHandler(context);
}
chatHandler.onHandleChatMessage(message);
}
catch (Exception e) {
}
}
}
}
}
Next Handle the Received Data from xmpp Class
public class ChatHandler {
private Context context;
private IntentService service;
private GEODBHelper myDBHelper;
private SessionManager session;
public ChatHandler(Context context, IntentService service) {
this.context = context;
this.service = service;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public ChatHandler(Context context) {
this.context = context;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public void onHandleChatMessage(Message message) {
try {
String data = URLDecoder.decode(message.getBody(), "UTF-8");
JSONObject messageObject = new JSONObject(data);
}
catch (Exception e) {
}
}
add to manifest
<service
android:name="com.app.xmpp.XmppService"
android:enabled="true" />
Start xmpp service
startService(new Intent(myclass.this, XmppService.class));
stop xmpp service
stopService(new Intent(getApplicationContext(), XmppService.class));
You can integrate Quickblox API it has multiple features like User Management, Chat, Group Chat, Video & Audio Calling.
Quickblox
Try this example https://github.com/blikoon/Rooster
It worked for me. I did my own messenger using this source
Goog luck
I have created an android chat application using XMPP server (openfire) and smack lib. When open my application i get connect =>connecting than a Oncreat SMACK exception appears. Which means that i can't establish a connexion with the server my code looks right but i cant figure out where is the probleme
here is the code
public class MyXMPP {
public static ArrayList<HashMap<String, String>> usersList=new ArrayList<HashMap<String, String>>();
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serverAddress;
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
Gson gson;
MyService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
public MyXMPP(MyService context, String serverAdress, String logiUser,
String passwordser) {
this.serverAddress = serverAdress;
this.loginUser = logiUser;
this.passwordUser = passwordser;
this.context = context;
init();
}
public static MyXMPP getInstance(MyService context,String server,
String user,String pass) {
if (instance == null) {
instance = new MyXMPP(context,server,user,pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
gson = new Gson();
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName("farah-pc");
config.setHost("farah-pc");
config.setPort(5222);
config.setDebuggerEnabled(true);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, caller + "=>connecting....", Toast.LENGTH_LONG).show();
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid, final String toid, final String msgid, final Stanza packet) {
}
});
Toast.makeText( context,"cava", Toast.LENGTH_SHORT).show();
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText( context,"(" + caller + ")" + "IOException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")","SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText( context,"(" + caller + ")" + "XMPPException: ", Toast.LENGTH_SHORT).show();
}
});
Log.e("connect(" + caller + ")", "XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
connection.login(loginUser,passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// SmackException.ConnectionException.getFailedAddresses() ;
//HostAddress.getException();
Toast.makeText( context,"alaaach", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public void sendMessage(ChatMessage chatMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(
chatMessage.receiver + "#"
+ context.getString(R.string.server),
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(chatMessage.getBody());
message.setType(Message.Type.normal);
try {
//if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
//} else {
login();
//}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
Toast.makeText( context,"not sending", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ReconnectionFailed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "REConnected!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(
mChatManagerListener);
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Connected!",
Toast.LENGTH_SHORT).show();
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
System.out.println("Body-----"+message.getBody());
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = new ChatMessage();
chatMessage.setBody(message.getBody());
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage) {
chatMessage.isMine = false;
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
}
//connect to server
private class MyOpenfireLoginTask extends AsyncTask<String, String, String> {
private Context mContext;
String username, password;
ProgressDialog dialog;
public MyOpenfireLoginTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(mContext);
dialog.setMessage(getResources().getString(R.string.loading_txt));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
username = params[0];
password = params[1];
Log.e("Login using ", username + " , " + password);
Config.config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setHost(Config.openfire_host_server_IP)
.setResource(Config.openfire_host_server_RESOURCE)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(Config.openfire_host_server_SERVICE)
.setPort(Config.openfire_host_server_CHAT_PORT)
.setDebuggerEnabled(true)
.build();
Config.conn1 = new XMPPTCPConnection(Config.config);
Config.conn1.setPacketReplyTimeout(5000);
try {
Config.conn1.connect();
if (Config.conn1.isConnected()) {
Log.w("app", "conn done");
}
Config.conn1.login();
if (Config.conn1.isAuthenticated()) {
Log.w("app", "Auth done");
} else {
Log.e("User Not Authenticated", "Needs to Update Password");
}
} catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (Config.conn1.isAuthenticated()) {
setUserPresence(0);
//store data in session
sharedPreferenceManager.setUsername(username);
sharedPreferenceManager.setUserPsw(password);
if (UserListActivity.mActivity != null) {
UserListActivity.mActivity.finish();
}
Intent intent = new Intent(mContext, HomeActivity.class);
mContext.startActivity(intent);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
if (SignupActivity.mActivity != null) {
SignupActivity.mActivity.finish();
}
finish();
} else {
Log.e(TAG, "username password wrong");
CommonUtils.commonToast(mContext, mContext.getResources().getString(R.string.invalid_uname_psw));
// CommonUtils.commonToast(mContext,mContext.getResources().getString(R.string.loading_txt));
}
}
}
// check connection is available or not !if not redirect to login screen.
public boolean isUserConnectedToServer(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "----->Connected");
setUserPresence(0);
return true;
} else {
Log.e(TAG, "----->Not connected");
setUserPresence(5);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
return false;
}
}
//disconnect user from server
public void logoutUser(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "-----isConnected------Logout");
setUserPresence(5);
Config.conn1.disconnect();
} else {
Log.e(TAG, "-----disconnect-------Not connected");
}
sharedPreferenceManager.clearData();
//stop background service
stopBackgroundService(mActivity);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Error I'm getting null point exception in Bluetooth when I'm starting a service.
LiveFragment.class
public class LiveFragment extends Fragment {
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
private BluetoothAdapter mBluetoothAdapter =null;
public BluetoothChatService mChatService = null;
private PowerManager.WakeLock wakeLock = null;
private PowerManager powerManager = null;
private String mConnectedDeviceName = null;
private boolean isServiceBound;
private boolean preRequisites = true;
private SharedPreferences prefs;
private BroadcastReceiver broadcastReceiver;
private Context c;
private AbstractGatewayService ab;
protected ImageView blue_onoffBut, gps_Button, obd_inidca, ss_button, bluetooth_indicator, gps_indicator,obd_connectButt;
protected TextView ss_Status,btStatusTextView,obdStatusTextView,gpsStatusTextView;
private LinearLayout vv;
protected BluetoothSocket sock = null;
public LiveFragment() {
// Required empty public constructor
}
private final Runnable mQueueCommands = new Runnable() {
public void run() {
Log.d(TAG, "Runnable mQueueCommands ()");
if (ab != null && ab.isRunning() && ab.queueEmpty()) {
queueCommands();
}
// run again in period defined in preferences
new Handler().postDelayed(mQueueCommands, 4000);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_live, container, false);
blue_onoffBut = (ImageView) view.findViewById(R.id.blutooth_butoon);
gps_Button = (ImageView) view.findViewById(R.id.gps_button);
obd_inidca = (ImageView) view.findViewById(R.id.obd_Indicator);
ss_button = (ImageView) view.findViewById(ssButton);
gps_indicator = (ImageView) view.findViewById(R.id.gps_indicator);
bluetooth_indicator = (ImageView) view.findViewById(R.id.bluetooth_indicator);
obd_connectButt = (ImageView) view.findViewById(R.id.Obd_Connect_Button);
ss_Status = (TextView) view.findViewById(R.id.statusTx);
btStatusTextView = (TextView) view.findViewById(R.id.blue);
obdStatusTextView = (TextView) view.findViewById(R.id.obd);
gpsStatusTextView = (TextView) view.findViewById(R.id.gps);
vv = (LinearLayout) view.findViewById(R.id.fragment_live_layout);
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
if (mBluetoothAdapter.isEnabled()) {
bluetooth_indicator.setImageResource(R.drawable.green_circle);
} else {
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
gps_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
else {
showToast("Already GPS is ON");
}
}
});
blue_onoffBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
showToast("Bluetooth Turned ON"+"\n"+"Connect Your OBD now");
bluetooth_indicator.setImageResource(R.drawable.green_circle);
mChatService = new BluetoothChatService(getActivity(), mHandler);
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
} else if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
mBluetoothAdapter.cancelDiscovery();
obd_inidca.setImageResource(R.drawable.red_circle);
showToast("Bluetooth Turned OFF");
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
}
});
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled() && mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
startLiveData();
} else if (!mBluetoothAdapter.isEnabled()) {
showToast("Turn ON Bluetooth to Continue");
}
else if (!(mChatService.getState() == BluetoothChatService.STATE_CONNECTED)){
showToast("Select your OBD to Start ");
}
}
});
obd_connectButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
}
else if (!mBluetoothAdapter.isEnabled()){
showToast("Turn ON Bluetooth to Connect OBD");
}
}
});
return view;
}
private ServiceConnection serviceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d(TAG, className.toString() + " service is bound");
isServiceBound = true;
ab = ((AbstractGatewayService.AbstractGatewayServiceBinder) binder).getService();
ab.setContext(getActivity());
Log.d(TAG, "Starting live data");
try {
ab.startService();
if (preRequisites)
btStatusTextView.setText("Connected");
} catch (IOException ioe) {
Log.e(TAG, "Failure Starting live data");
btStatusTextView.setText("Connection failed");
doUnbindService();
}
}
#Override
protected Object clone() throws CloneNotSupportedException {
Log.d(TAG, "CloneNotSupportedException ");
return super.clone();
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d(TAG, className.toString() + " service is unbound");
isServiceBound = false;
}
};
public static String LookUpCommand(String txt) {
Log.d(TAG, "LookUpCommand() ");
for (AvailableCommandNames item : AvailableCommandNames.values()) {
if (item.getValue().equals(txt)) return item.name();
}
return txt;
}
public void updateTextView(final TextView view, final String txt) {
Log.d(TAG, "updateTextView() ");
new Handler().post(new Runnable() {
public void run() {
view.setText(txt);
}
});
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void stateUpdate(ObdCommandJob job) {
final String cmdName = job.getCommand().getName();
String cmdResult = "";
final String cmdID = LookUpCommand(cmdName);
Log.d(TAG, "stateUpdate() ");
if (job.getState().equals(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR)) {
cmdResult = job.getCommand().getResult();
if (cmdResult != null && isServiceBound) {
obdStatusTextView.setText(cmdResult.toLowerCase());
}
} else if (job.getState().equals(ObdCommandJob.ObdCommandJobState.BROKEN_PIPE)) {
if (isServiceBound)
stopLiveData();
} else if (job.getState().equals(ObdCommandJob.ObdCommandJobState.NOT_SUPPORTED)) {
cmdResult = "NA";
} else {
cmdResult = job.getCommand().getFormattedResult();
if (isServiceBound)
obdStatusTextView.setText("Receiving data...");
}
cmdResult.replace("NODATA", "0");
if (vv.findViewWithTag(cmdID) != null) {
TextView existingTV = (TextView) vv.findViewWithTag(cmdID);
existingTV.setText(cmdResult);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "No Bluetooth Feature in Device", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gps_indicator.setImageResource(R.drawable.red_circle);
}
if(mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
}
#Override
public void onResume() {
super.onResume();
powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ObdReader");
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gps_indicator.setImageResource(R.drawable.green_circle);
} else {
gps_indicator.setImageResource(R.drawable.red_circle);
}
EventBus.getDefault().register(this);
if(mBluetoothAdapter.isEnabled()) {
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "Pausing..");
releaseWakeLockIfHeld();
EventBus.getDefault().unregister(this);
}
private void showToast(String message) {
final Toast toast = Toast.makeText(getContext(), message, Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 500);
}
#Override
public void onDestroy() {
/* unregisterReceiver(mReceiver);*/
super.onDestroy();
releaseWakeLockIfHeld();
if (mChatService != null) {
mChatService.stop();
}
if (isServiceBound) {
doUnbindService();
}
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
showToast("Take Care!");
}
private void startLiveData() {
if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
Log.d(TAG, "Starting live data..");
ss_Status.setText("Stop");
ss_Status.setTextColor(getResources().getColor(R.color.colorRed));
wakeLock.acquire();
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ss_Status.setText("Go Live");
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
stopLiveData();
}
});
doBindService();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver), new IntentFilter(OBD_GATEWAY_SERVICE));
new Handler().post(mQueueCommands);
}
}
private void stopLiveData() {
Log.d(TAG, "Stopping live data..");
releaseWakeLockIfHeld();
new Handler().removeCallbacks(mQueueCommands);
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ss_Status.setText("Go Live");
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
startLiveData();
}
});
doUnbindService();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
private void queueCommands() {
Log.d(TAG, "LiveFragment queueCommands() ");
if (isServiceBound) {
for (ObdCommand Command : ObdConfig.getCommands()) {
if (prefs.getBoolean(Command.getName(), true))
ab.queueJob(new ObdCommandJob(Command));
}
}
}
private void doBindService() {
if (!isServiceBound) {
Log.d(TAG, "Binding OBD service..");
if (preRequisites) {
btStatusTextView.setText("Connecting.....");
Intent serviceIntent = new Intent(getActivity(),ObdGatewayService.class);
getActivity().bindService(serviceIntent, serviceConn, Context.BIND_AUTO_CREATE);
}
}
}
private void doUnbindService() {
if (isServiceBound) {
if (ab.isRunning()) {
ab.stopService();
if (preRequisites)
btStatusTextView.setText("Ready...");
}
Log.d(TAG, "Unbinding OBD service..");
getActivity().unbindService(serviceConn);
isServiceBound = false;
obdStatusTextView.setText("Disconnected");
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
obd_inidca.setImageResource(R.drawable.green_circle);
break;
case BluetoothChatService.STATE_CONNECTING:
obd_inidca.setImageResource(R.drawable.orange_circle);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
obd_inidca.setImageResource(R.drawable.red_circle);
break;
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
obd_inidca.setImageResource(R.drawable.green_circle);
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
try {
connectDevice(data, true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void connectDevice(Intent data, boolean secure) throws IOException {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice dev = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(dev, secure);
}.
This is ObdGateway service class:
public class ObdGatewayService extends AbstractGatewayService {
private static final String TAG = ObdGatewayService.class.getName();
#Inject
SharedPreferences prefs;
private BluetoothDevice dev = null;
private BluetoothSocket sock = null;
private BluetoothChatService mChatservice = null;
private BluetoothAdapter bluetoothAdapter =null;
public final static String JOB_NAME_STAMP = "Name";
public final static String JOB_STATE_STAMP = "State";
public final static String JOB_RESULT_STAMP = "Result";
public final static String JOB_FORMATED_RESULT_STAMP = "Formated REsult";
public final static String OBD_GATEWAY_SERVICE = "com.samplersoft.saz.Obd.ObdGatewayService";
public void startService() throws IOException {
Log.d(TAG, "Starting service..");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// get the remote Bluetooth device
if(mChatservice.getState() != BluetoothChatService.STATE_CONNECTED){
Toast.makeText(ctx, "No Bluetooth device selected", Toast.LENGTH_LONG).show();
// log error
Log.e(TAG, "No Bluetooth device has been selected.");
stopService();
throw new IOException();
}
else
{
Log.d(TAG, "Stopping Bluetooth discovery.");
bluetoothAdapter.cancelDiscovery();
try {
startObdConnection();
} catch (Exception e) {
Log.e(
TAG,
"There was an error while establishing connection. -> "
+ e.getMessage()
);
// in case of failure, stop this service.
stopService();
throw new IOException();
}
}
}
private void startObdConnection() throws IOException {
Log.d(TAG, "Starting OBD connection..");
isRunning = true;
if(mChatservice.getState() == BluetoothChatService.STATE_CONNECTED){
// Let's configure the connection.
Log.d(TAG, "Queueing jobs for connection configuration..");
queueJob(new ObdCommandJob(new ObdResetCommand()));
try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
queueJob(new ObdCommandJob(new EchoOffCommand()));
queueJob(new ObdCommandJob(new EchoOffCommand()));
queueJob(new ObdCommandJob(new LineFeedOffCommand()));
queueJob(new ObdCommandJob(new TimeoutCommand(62)));
// Get protocol from preferences
queueJob(new ObdCommandJob(new SelectProtocolCommand(ObdProtocols.valueOf("AUTO"))));
// Job for returning dummy data
queueJob(new ObdCommandJob(new AmbientAirTemperatureCommand()));
queueCounter = 0L;
Log.d(TAG, "Initialization jobs queued.");
}
else {
stopService();
throw new IOException();
}
}
#Override
public void queueJob(ObdCommandJob job) {
// This is a good place to enforce the imperial units option
//job.getCommand().useImperialUnits(prefs.getBoolean(ConfigActivity.IMPERIAL_UNITS_KEY, false));
// Now we can pass it along
super.queueJob(job);
}
protected void executeQueue() throws InterruptedException {
Log.d(TAG, "Executing queue..");
while (!Thread.currentThread().isInterrupted()) {
ObdCommandJob job = null;
try {
job = jobsQueue.take();
// log job
Log.d(TAG, "Taking job[" + job.getId() + "] from queue..");
if (job.getState().equals(ObdCommandJob.ObdCommandJobState.NEW)) {
Log.d(TAG, "Job state is NEW. Run it..");
job.setState(ObdCommandJob.ObdCommandJobState.RUNNING);
if (sock.isConnected()) {
job.getCommand().run(sock.getInputStream(), sock.getOutputStream());
} else {
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
Log.e(TAG, "Can't run command on a closed socket.");
}
} else
// log not new job
Log.e(TAG,
"Job state was not new, so it shouldn't be in queue. BUG ALERT!");
} catch (InterruptedException i) {
Thread.currentThread().interrupt();
} catch (UnsupportedCommandException u) {
if (job != null) {
job.setState(ObdCommandJob.ObdCommandJobState.NOT_SUPPORTED);
}
Log.d(TAG, "Command not supported. -> " + u.getMessage());
} catch (IOException io) {
if (job != null) {
if(io.getMessage().contains("Broken pipe"))
job.setState(ObdCommandJob.ObdCommandJobState.BROKEN_PIPE);
else
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
}
Log.e(TAG, "IO error. -> " + io.getMessage());
} catch (Exception e) {
if (job != null) {
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
}
Log.e(TAG, "Failed to run command. -> " + e.getMessage());
}
ObdCommandJob job2 = job;
if(job2 !=null)
EventBus.getDefault().post(job2);
}
}
public void stopService() {
Log.d(TAG, "Stopping service..");
jobsQueue.clear();
isRunning = false;
if (sock != null)
// close socket
try {
sock.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
// kill service
stopSelf();
}
public boolean isRunning() {
return isRunning;
}
}.
This is Abstract Class where service method gets called from from Livefragment Class from serivceConnection().
public abstract class AbstractGatewayService extends RoboService {
private static final String TAG = AbstractGatewayService.class.getName();
private final IBinder binder = new AbstractGatewayServiceBinder();
protected Context ctx;
protected boolean isRunning = false;
protected Long queueCounter = 0L;
protected BlockingQueue<ObdCommandJob> jobsQueue = new LinkedBlockingQueue<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
executeQueue();
} catch (InterruptedException e) {
t.interrupt();
}
}
});
protected LocalBroadcastManager broadcastManager;
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Creating service..");
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
t.start();
Log.d(TAG, "Service created.");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroying service...");
t.interrupt();
broadcastManager = LocalBroadcastManager.getInstance(this);
Log.d(TAG, "Service destroyed.");
}
public boolean isRunning() {
return isRunning;
}
public boolean queueEmpty() {
return jobsQueue.isEmpty();
}
public void queueJob(ObdCommandJob job) {
queueCounter++;
Log.d(TAG, "Adding job[" + queueCounter + "] to queue..");
job.setId(queueCounter);
try {
jobsQueue.put(job);
Log.d(TAG, "Job queued successfully.");
} catch (InterruptedException e) {
job.setState(ObdCommandJob.ObdCommandJobState.QUEUE_ERROR);
Log.e(TAG, "Failed to queue job.");
}
}
public void setContext(Context c) {
ctx = c;
}
abstract protected void executeQueue() throws InterruptedException;
abstract public void startService() throws IOException;
abstract public void stopService();
public class AbstractGatewayServiceBinder extends Binder {
public AbstractGatewayService getService() {
return AbstractGatewayService.this;
}
}
}.
You are getting the exception because in class ObdGatewayService your class member mChatservice is not the same as mChatservice in class LiveFragment
They are just different member variables
mChatservice gets assigned like this in your Fragment
mChatService = new BluetoothChatService(getActivity(), mHandler);
You need to pass this reference to ObdGatewayService 's startService() like this where ever you are instantiating/invoking it:-
ObdGatewayService ogs;
....
ogs.startservice(mChatservice); // This is fragment's member reference
And in ObdGatewayService you have to assign it accordingly:-
public void startService(BluetoothChatService _mChatservice) throws IOException {
Log.d(TAG, "Starting service..");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mChatservice = _mChatservice //Assignment YOU ARE MISSING THIS
.......
.......
}
This question already has answers here:
How to detect incoming calls, in an Android device?
(13 answers)
Closed 6 years ago.
Here, I'm creating a application to start flash when an sms is recieved and an incoming call is recieved. The flash is working on recieving sms but not on call, why? Can anyone help? I'm stuck on this since many days. Thanks in advance, my code is given below. Flash only performs on recieving sms but not on recieving calls. Expecting your guidence. When I searched regarding this I am getting only the Classes and methods to create my own app. Requesting for the explanation
public class SMSReceiver extends BroadcastReceiver {
Boolean call;
private Camera camera;
int count;
long delaytime;
Editor editor;
String flashtype;
private boolean hasFlash;
private boolean isFlashOn;
private boolean isFlashblinking;
private boolean mActive;
private Handler mHander;
private final Runnable mRunnable;
private boolean mSwap;
private Context mcontext;
AudioManager myAudioManager;
String noofblinks;
int numbofblink;
Parameters params;
SharedPreferences pref;
StringBuilder result;
Boolean ring;
Boolean silent;
Boolean sms;
String timetoblink;
Boolean vibrate;
public class PhoneListener extends PhoneStateListener {
private Context context;
public PhoneListener(Context c) {
Log.i("CallRecorder", "PhoneListener constructor");
this.context = c;
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case 0:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
case 1:
try {
if (SMSReceiver.this.call.booleanValue()) {
if (SMSReceiver.this.myAudioManager.getRingerMode() == 0
&& SMSReceiver.this.silent.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 1
&& SMSReceiver.this.vibrate.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 2
&& SMSReceiver.this.ring.booleanValue()) {
SMSReceiver.this.flash();
}
}
} catch (Exception e3) {
}
case 2:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e4) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e5) {
}
}
default:
}
}
}
public SMSReceiver() {
this.mHander = new Handler();
this.mActive = false;
this.mSwap = true;
this.isFlashblinking = true;
this.count = 0;
this.mRunnable = new Runnable() {
#Override
// TODO Auto-generated method stub
public void run() {
try {
SMSReceiver sMSReceiver = SMSReceiver.this;
sMSReceiver.count++;
} catch (Exception e) {
}
if (SMSReceiver.this.mActive) {
if (SMSReceiver.this.count >= SMSReceiver.this.numbofblink * 2) {
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
if (SMSReceiver.this.isFlashOn) {
SMSReceiver.this.turnOffFlash();
} else {
SMSReceiver.this.turnOnFlash();
}
try {
SMSReceiver.this.mHander.postDelayed(
SMSReceiver.this.mRunnable,
SMSReceiver.this.delaytime);
} catch (Exception e3) {
}
}
}
};
}
public void onReceive(Context context, Intent intent) {
try {
this.mcontext = context;
this.count = 0;
try {
this.pref = PreferenceManager
.getDefaultSharedPreferences(this.mcontext);
this.editor = this.pref.edit();
this.call = Boolean.valueOf(this.pref.getBoolean("call", true));
this.sms = Boolean.valueOf(this.pref.getBoolean("sms", true));
this.timetoblink = this.pref.getString("blinktime", "200");
this.noofblinks = this.pref.getString("noofblinks", "5");
this.ring = Boolean.valueOf(this.pref.getBoolean("ring", true));
this.vibrate = Boolean.valueOf(this.pref.getBoolean("vibrate",
true));
this.silent = Boolean.valueOf(this.pref.getBoolean("silent",
true));
this.flashtype = this.pref.getString("flashtype", "1");
this.delaytime = Long.parseLong(this.timetoblink);
this.numbofblink = Integer.parseInt(this.noofblinks);
this.myAudioManager = (AudioManager) this.mcontext
.getSystemService("audio");
} catch (Exception e) {
}
((TelephonyManager) this.mcontext.getSystemService("phone"))
.listen(new PhoneListener(context), 32);
} catch (Exception e2) {
}
}
public void flash() {
try {
this.hasFlash = this.mcontext.getPackageManager().hasSystemFeature(
"android.hardware.camera.flash");
if (this.hasFlash) {
getCamera();
startStrobe();
return;
}
AlertDialog alert = new Builder(this.mcontext).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
} catch (Exception e) {
}
}
private void getCamera() {
if (this.camera == null) {
try {
this.camera = Camera.open();
this.params = this.camera.getParameters();
} catch (Exception e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
try {
if (!this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
if (this.flashtype.equals("2")) {
this.params.setFlashMode("torch");
} else if (this.flashtype.equals("3")) {
this.params.setFlashMode("torch");
} else {
this.params.setFlashMode("torch");
}
this.camera.setParameters(this.params);
this.camera.startPreview();
this.isFlashOn = true;
}
} catch (Exception e) {
}
}
private void turnOffFlash() {
try {
if (this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
this.params.setFlashMode("off");
this.camera.setParameters(this.params);
this.camera.stopPreview();
this.isFlashOn = false;
}
} catch (Exception e) {
}
}
private void startStrobe() {
try {
this.mActive = true;
this.mHander.post(this.mRunnable);
} catch (Exception e) {
}
}
}
This is doable
follow this link for the same
http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61
Make a broadcast receiver to know about incoming call
write that code in AndroidManifes.xml
<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and make a new a class like that.
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
// Run the flash in that line
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
}
}
I'm trying too login to the android app that i have created whose authentication will be done using the username and password registered in ejabberd. The connection is successfully established but i'm not abe to login. It gives an error namely -
"ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element"
The log is:
04-15 19:27:45.052 31421-31421/com.synergy.allie.ecm D/calling xmpp connect: started
04-15 19:27:45.052 31421-31749/com.synergy.allie.ecm D/Connect() Function: =>connecting....
04-15 19:27:45.072 31421-31421/com.synergy.allie.ecm D/LoginActivity: onServiceConnected
04-15 19:27:45.102 31421-31751/com.synergy.allie.ecm I/System.out: 07:27:45 PM SENT (0): http://etherx.jabber.org/streams' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://etherx.jabber.org/streams' id='284868730' from='allen' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://jabber.org/protocol/caps' hash='sha-1' node='http://www.process-one.net/en/ejabberd/' ver='SLr01mk3X636tk4sDXYXPXsNNcE='/>http://jabber.org/features/iq-register'/>PLAINDIGEST-MD5SCRAM-SHA-1
04-15 19:27:45.142 31421-31749/com.synergy.allie.ecm D/xmpp: Connected!
04-15 19:28:45.102 31421-31752/com.synergy.allie.ecm W/AbstractXMPPConnection: Connection closed with error
org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1148)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
at java.lang.Thread.run(Thread.java:856)
04-15 19:28:45.112 31421-31752/com.synergy.allie.ecm D/xmpp: ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
public class MyXMPP
{
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serverAddress;
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
Gson gson;
MyService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
Boolean logon;
public MyXMPP(MyService context, String serverAdress, String logiUser,
String passwordser) {
this.serverAddress = serverAdress;
this.loginUser = logiUser;
this.passwordUser = passwordser;
this.context = context;
init();
}
public static MyXMPP getInstance(MyService context, String server,
String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, server, user, pass);
instanceCreated = true;
}
return instance;
}
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
gson = new Gson();
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost("***.***.***.***");
config.setPort(5222);
config.setDebuggerEnabled(true);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, caller + "Trying to establish a connection!", Toast.LENGTH_LONG).show();
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid,
final String toid, final String msgid,
final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "IOException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "SMACKException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "XMPPException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("connect(" + caller + ")",
"XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login()
{
try
{
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Praise Jesus! We're connected to the Xmpp server!");
logon=true;
}
catch (XMPPException | SmackException | IOException e)
{
logon=false;
e.printStackTrace();
}
catch (Exception e)
{
logon=false;
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public void sendMessage(ChatMessage chatMessage) {
String body = gson.toJson(chatMessage);
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(chatMessage.receiver
+ "#" + context.getString(R.string.server),
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp.SendMessage()", "msg Not sent!" + e.getMessage());
}
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionClosedOn Error! "+arg0.getMessage());
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ReconnectionFailed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "REConnected!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(
mChatManagerListener);
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Connected!",
Toast.LENGTH_SHORT).show();
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = gson.fromJson(
message.getBody(), ChatMessage.class);
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage) {
chatMessage.isMine = false;
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
}
try this code
public void initConnection(String user, String pass) throws XMPPException {
// TODO Auto-generated method stub
String SERVER_HOST = "192.168.1.199";
int SERVER_PORT = 5222;
String SERVICE_NAME = "Allen";
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMPPTCPConnectionConfiguration.Builder connConfig = XMPPTCPConnectionConfiguration
.builder();
connConfig
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
connConfig.setUsernameAndPassword(user, pass);
connConfig.setServiceName(SERVICE_NAME);
connConfig.setHost(SERVER_HOST);
connConfig.setPort(SERVER_PORT).setCompressionEnabled(false);
connConfig.setDebuggerEnabled(true);
connConfig.setConnectTimeout(25000);
XMPPTCPConnectionConfiguration configuration = connConfig.build();
// XMPPTCPConnection.setUseStreamManagementDefault(true);
// XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
// XMPPTCPConnection.setReplyToUnknownIqDefault(true);
connection = new XMPPTCPConnection(configuration);
connection.setUseStreamManagement(true);
connection.setUseStreamManagementResumption(true);
connection.setReplyToUnknownIq(true);
connection.setPacketReplyTimeout(25000);
ReconnectionManager manager = ReconnectionManager.getInstanceFor(connection);
manager.setFixedDelay(15);
ReconnectionManager.setDefaultReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY);
manager.enableAutomaticReconnection();
try {
connection.connect();
connection.login();
//logIn();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}