Java – Android service activity 2 mode communication
In my team's Android application, I have a service running from startup. It communicates with the server to perform operations such as logging in, registering, chatting between phones and updating the phone database
I need to make my service communicate with two-way activities: for example, I am processing login activities, the user name and password are strings obtained from the text fields on the application screen, and I have been able to send authorization commands to the server through them
public void loginPressed(View v){ usernameStr = usernameField.getText().toString(); passwordStr = passwordField.getText().toString(); if (!bound) return; Bundle b = new Bundle(); Message msg = Message.obtain(null,ChatService.LOGIN); try { b.putString("username",usernameStr); b.putString("password",passwordStr); msg.setData(b); messenger.send(msg); } catch (remoteexception e) { }
It can work as I expected When the server responds to a message indicating whether the login is successful, I need it to pass the message back to the activity so that I can start the main activity. If it is successful or prompt to re-enter, if not
I try to use MSG Replyto field to get the return messenger to send back information, but when I run the application, it will close abnormally with a null pointer. I don't know why this happens This code seems to be the culprit:
private class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch(msg.what) { case LOGIN: Bundle b = msg.getData(); String username = b.getString("username"); String password = b.getString("password"); String loginMessage = TCPCall.login(username,password); connection.sendMessage(loginMessage); String loginReturn = connection.retrieveMessage(); Message m; Scanner s = new Scanner(loginReturn); s.useDelimiter(","); String c = s.next(); String status = s.next(); String message = s.next(); if (status.equals("OK")) { m = Message.obtain(null,LoginActivity.OK); try { msg.replyTo.send(m); } catch (remoteexception e) {} } else { m = Message.obtain(null,LoginActivity.ERR); try { msg.replyTo.send(m); } catch (remoteexception e) {} } break;
The null pointer appears to come from
msg.replyTo.send(m);
Code lines in two cases (login success and login failure)
Any help in solving this problem will be appreciated:)
Solution
As Greg pointed out in his comments You need to set MSG replyTo = messenger; Int where he sent the original mail
An example can be found here: http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html