I have found a working demo and successfully worked with that.but the problem is i have implemented it with minimum version 10 where StrictPolicy is importable.now i want min sdk version 1.6 or above to work with Bump.
I have also seen that AsysncTask for BindService can be used but not worked for me.suggest something what wrong i am doing
int sdkVersion = android.os.Build.VERSION.SDK_INT;
if(sdkVersion>9)
{
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}catch (Exception e) {
// TODO: handle exception
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
filter.addAction(BumpAPIIntents.DATA_RECEIVED);
filter.addAction(BumpAPIIntents.NOT_MATCHED);
filter.addAction(BumpAPIIntents.MATCHED);
filter.addAction(BumpAPIIntents.CONNECTED);
filter.addAction(BumpAPIIntents.DISCONNECTED);
filter.addAction(BumpAPIIntents.BUMPED);
this.registerReceiver(receiver, filter);
//txtReceived=(TextView)findViewById(R.id.txtReceived);
//bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
new BindService().execute();
}
class BindService extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("done");
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} */
#Override
public void onDestroy()
{
super.onDestroy();
try {
unbindService(connection);
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder)
{
Log.i("Bump", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
try
{
api.configure("KEY_HERE", "Some text..");
}
catch (RemoteException e)
{
Log.i("Bump", "api.configured failed");
}
}
#Override
public void onServiceDisconnected(ComponentName className)
{
Log.i("Bump", "onServiceDisconnected");
}
};
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
try {
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
Log.i("Bump", "DATA_RECEIVED");
Log.i("Bump", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0)));
Log.i("Bump", "Data: " + new String(intent.getByteArrayExtra("data")));
//AlertDialog.Builder diaBuilder=
} else if (action.equals(BumpAPIIntents.MATCHED)) {
Log.i("Bump", "MATCHED");
api.confirm(intent.getLongExtra("proposedChannelID", 0), true);
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
Log.i("Bump", "CHANNEL_CONFIRMED");
api.send(intent.getLongExtra("channelID", 0), (StaticData.strUserId + ","+ StaticData.strHomeName + ","+ StaticData.strUserImgUrl).getBytes());
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
Log.i("Bump", "CONNECTED");
api.enableBumping();
}
else if (action.equals(BumpAPIIntents.DISCONNECTED)) {
Log.i("Bump", "DISCONNECTED");
} else if (action.equals(BumpAPIIntents.BUMPED)) {
Log.i("Bump", "BUMPED");
}
else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Log.i("Bump", "NOT_MATCHED");
}
else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID)) {
Log.i("Bump", "CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID");
}
else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID)) {
Log.i("Bump", "CHANNEL_CONFIRMED_EXTRA_CHANNEL_ID");
}
} catch (RemoteException e) {}
}
};
the working demo i have used above is docs.google.com/open?id=0B8f-N2PC8e0vU0gxRm1jaG51RGM
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
Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}
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?".
Service class:
private IBinder mBinder ;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service","started");
new Connect().execute("");
return Service.START_STICKY;
}
private class Connect extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
ConnectionConfiguration connConfig = new ConnectionConfiguration(
HOST, PORT, SERVICE);
final XMPPConnection connection = new XMPPConnection(connConfig);
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try {
connection.connect();
// SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(USERNAME, PASSWORD);
Log.i("NetWorkConnection",
"Logged in as " + connection.getUser());
System.out.println(connection);
setConnection(connection);
} catch (XMPPException ex) {
Log.e("NetWorkConnection", "Failed to log in as "
+ USERNAME);
Log.e("NetWorkConnection", ex.toString());
setConnection(null);
}
}});
t.start();
return null;
}
}
public void setConnection(XMPPConnection connection) {
NetworkConnection.connection = connection;
}
public class MyBinder extends Binder
{
NetworkConnection getService() {
return NetworkConnection.this;
}
}
public XMPPConnection getconnection()
{
if (connection != null) {
Log.d("NetworkConnection","connection send");
return connection;
}
else
{
Log.d("NetworkConnection","connection null");
return null;
}
}
}
Activity Class:
private NetworkConnection service;
XMPPConnection connection=NetworkConnection.connection;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
next=(Button)findViewById(R.id.bRetry);
if(!isMyServiceRunning())
{
Intent i=new Intent(this,NetworkConnection.class);
startService(i);
}
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.println(connection);
if(connection!=null)
{
Intent i = new Intent (getApplicationContext(),UserIndex.class);
startActivity(i);
}else{
Intent i = new Intent(SignIn.this,SignIn.class);
startActivity(i);
}
}
});
}
#Override
protected void onResume() {
bindService(new Intent(this, NetworkConnection.class), mConnection,
Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
protected void onPause() {
unbindService(mConnection);
super.onPause();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
service = ((NetworkConnection.MyBinder) binder).getService();
Log.d("Service","Connected");
System.out.println("service connection methoddd");
connection=service.getconnection();
}
public void onServiceDisconnected(ComponentName className) {
connection=null;
service = null;
}
};
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (NetworkConnection.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
I am creating a chat application using XMPP and asmack, So i used service. But the problem is that when i start the service onServiceConnected method never execute.That is why when i retrieve the connection object from service it always give null value. I have not much idea about it . please guide me.
Whenever i am running my application I am getting "Service connected" message but after that the BroadcastReceiver are no responding.
what is the problem ?
Can anyone tell me what should i do?
public class BumpTest extends Activity
{
private IBumpAPI api;
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
try {
api.configure("8836a26d3545410c9905d90528b2153a",
"ram");//8836a26d3545410c9905d90528b2153a,3826a0e77b284c05960d4513e87c4a88
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
try {
Log.i("Bump Test", "In Receive " );
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
Log.i("Bump Test", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0)));
Log.i("Bump Test", "Data: " + new String(intent.getByteArrayExtra("data")));
} else if (action.equals(BumpAPIIntents.MATCHED)) {
long channelID = intent.getLongExtra("proposedChannelID", 0);
Log.i("Bump Test", "Matched with: " + api.userIDForChannelID(channelID));
api.confirm(channelID, true);
Log.i("Bump Test", "Confirm sent");
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
long channelID = intent.getLongExtra("channelID", 0);
Log.i("Bump Test", "Channel confirmed with " + api.userIDForChannelID(channelID));
api.send(channelID, "Hello, world!".getBytes());
} else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Log.i("Bump Test", "Not matched.");
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
Log.i("Bump Test", "Connected to Bump...");
api.enableBumping();
}else{
System.out.println("inn broadcast rcvr ::: "+api.toString());
}
} catch (RemoteException e) {}
}
};
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(IBumpAPI.class.getName()),
connection, Context.BIND_AUTO_CREATE);
Log.i("BumpTest", "boot");
IntentFilter filter = new IntentFilter();
filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
filter.addAction(BumpAPIIntents.DATA_RECEIVED);
filter.addAction(BumpAPIIntents.NOT_MATCHED);
filter.addAction(BumpAPIIntents.MATCHED);
filter.addAction(BumpAPIIntents.CONNECTED);
registerReceiver(receiver, filter);
//txtReceived=(TextView)findViewById(R.id.txtReceived);
//bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
new BindService().execute();
}
#SuppressLint("NewApi")
class BindService extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
return null;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("done");
}
}
public void onStart() {
Log.i("BumpTest", "onStart");
super.onStart();
}
public void onRestart() {
Log.i("BumpTest", "onRestart");
super.onRestart();
}
public void onResume() {
Log.i("BumpTest", "onResume");
super.onResume();
}
public void onPause() {
Log.i("BumpTest", "onPause");
super.onPause();
}
public void onStop() {
Log.i("BumpTest", "onStop");
super.onStop();
}
public void onDestroy() {
Log.i("BumpTest", "onDestroy");
super.onDestroy();
try {
unbindService(connection);
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
}