Defining Passkey for Android Bluetooth Connection - java

need your help again :
I want to establish a connection to a obd2-bluetooth-adapter. For that reason i had a look at the BluetoothChat-Example from the AndroidSDK. I am able to establish a connection to my computer, but i am not able to pair my android tablet with my odb2-bluetooth-adapter (elm327). Found some hints, for instance :
myRemoteBluetoothDevice.setPassKey(....);
First, i can not use the function on 'myRemoteBluetoothDevice' - and then i don't know where to use this function. Within the connect-Thread ?
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
}
I think a possible solution would be to implement a event-listener or something like this, which is called when the remote device needs a passcode ? But where i have to implement it ? And where i have to use it ?
Can somebody help me out there ?
Thanks in advance !!!
PS : My App is based on the following example :
https://android.googlesource.com/platform/development/+/25b6aed7b2e01ce7bdc0dfa1a79eaf009ad178fe/samples/BluetoothChat/src/com/example/android/BluetoothChat/BluetoothChatService.java
Greetings.
EDIT :
Tried to implement the first answer :
My BroadcastReceiver :
private final BroadcastReceiver mReceiverRequiresPin = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
try {
BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Class<?> btDeviceInstance = Class.forName(BluetoothDevice.class.getCanonicalName());
Method convert = btDeviceInstance.getMethod("convertPinToBytes", String.class);
byte[] pin = (byte[]) convert.invoke(newDevice, "1234");
Method setPin = btDeviceInstance.getMethod("setPin", byte[].class);
boolean success = (Boolean) setPin.invoke(newDevice, pin);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
And my connect-method, where i register the broadcastReceiver :
private void connect(CordovaArgs args, boolean secure,
CallbackContext callbackContext) throws JSONException {
final String actionPinRequested = "android.bluetooth.device.action.PAIRING_REQUEST";
IntentFilter intentFilterPinRequested = new IntentFilter(actionPinRequested);
cordova.getActivity().registerReceiver(mReceiverRequiresPin, intentFilterPinRequested);
String macAddress = args.getString(0);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
if (device != null) {
connectCallback = callbackContext;
bluetoothSerialService.connect(device, secure);
PluginResult result = new PluginResult(
PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} else {
callbackContext.error("Could not connect to " + macAddress);
}
}
Would really appreciate your help !
Thanks in advance.
No one has a hint ??

Register a broadcast listener for: android.bluetooth.device.action.PAIRING_REQUEST.
In the onrecieve:
BluetoothDevice newDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Class<?> btDeviceInstance = Class.forName(BluetoothDevice.class.getCanonicalName());
Method convert = btDeviceInstance.getMethod("convertPinToBytes", String.class);
byte[] pin = (byte[]) convert.invoke(newDevice, "1234");
Method setPin = btDeviceInstance.getMethod("setPin", byte[].class);
success = (Boolean) setPin.invoke(newDevice, pin);

Related

UserRecoverableAuthIOException with gmail-api after authentication

I am using Gmail api and many users are complaining that sending emails does not work. For most users it works fine and I am not able to reproduce the issue. In Firebase I get the following crash report.
Non-fatal Exception: com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:297)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.dummydomain.myapp.EmailUtils.sendMessage(EmailUtils.java:397)
(...)
Caused by com.google.android.gms.auth.d: NeedPermission
at com.google.android.gms.auth.zze.zzb(zze.java:13)
at com.google.android.gms.auth.zzd.zza(zzd.java:77)
at com.google.android.gms.auth.zzd.zzb(zzd.java:20)
at com.google.android.gms.auth.zzd.getToken(zzd.java:7)
at com.google.android.gms.auth.zzd.getToken(zzd.java:5)
at com.google.android.gms.auth.zzd.getToken(zzd.java:2)
at com.google.android.gms.auth.GoogleAuthUtil.getToken(GoogleAuthUtil.java:55)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:267)
at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:292)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.dummydomain.myapp.EmailUtils.sendMessage(EmailUtils.java:397)
(...)
Below are the essentials of my authentication process. Manifest.permission.GET_ACCOUNTS is already granted at this point, and the appropriate API things in the Google Cloud Console are correctly configured and my app is verified for using the sensitive permission/scope GMAIL_SEND.
private void authenticate() {
String[] SCOPES = {GmailScopes.GMAIL_SEND};
GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(
context,
Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
startActivityForResult(mCredential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
}
// which returns in
public void onActivityResult(...) {
// (...)
switch(requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
// Check if not a gmail account, since gmail api only works with that gmail accounts...
if(!accountName.contains("#gmail.com") && !accountName.contains("#googlemail.com")){
// --> tell user to select a google account
return;
}
mCredential.setSelectedAccount(new Account(accountName, BuildConfig.APPLICATION_ID));
// Got account, now test if we have access
new CheckAccessTask().execute();
}else{
// (...)
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode != Activity.RESULT_OK) {
// choose new account
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}else{
// Got authorization, so test email
new CheckAccessTask().execute();
}
break;
}
}
private class CheckAccessTask extends AsyncTask<Void, Void, Boolean> {
private Exception mLastError = null;
#Override
protected Boolean doInBackground(Void... params) {
try {
// Check if we got token - will crash with UserRecoverableAuthException
// if user didn't accept the google consent screen
mCredential.getToken();
// access granted, return true
return true;
} catch (Exception e) {
mLastError = e;
cancel(true);
return false;
}
}
#Override
protected void onCancelled() {
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
// Play Services not found --> cancel activation
} else if (mLastError instanceof UserRecoverableAuthException) {
startActivityForResult(((UserRecoverableAuthException) mLastError).getIntent(), REQUEST_AUTHORIZATION);
} else if (mLastError instanceof UserRecoverableAuthIOException) {
startActivityForResult(((UserRecoverableAuthIOException) mLastError).getIntent(), REQUEST_AUTHORIZATION);
} else {
// Other error --> cancel activation
}
} else {
// --> cancel activation
}
}
#Override
protected void onPostExecute(Boolean accessGranted) {
if (accessGranted){
// SUCCESS! Save email in shared preferences for later use
String accountName = mCredential.getSelectedAccountName();
prefs.putString(Constants.SENDER_ACCOUNT, accountName);
}
}
}
Essentials of sending email process (in actual code emails are HTML)
private void sendEmail(){
GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(
context,
Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
// set sender account
String senderAccount = prefs.getString(Constants.SENDER_ACCOUNT, null);
if(senderAccount == null) return; // Authentication not complete
mCredential.setSelectedAccount(new Account(senderAccount, BuildConfig.APPLICATION_ID));
// Initialize service object
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
Gmail mGmailApiService = new Gmail.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("My-App")
.build();
// Construct email
com.google.api.services.gmail.model.Message message;
try {
// create MimeMessage
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject("Test email");
mimeMessage.setText("Hello this is an email sent from android");
mimeMessage.setFrom(new InternetAddress(mCredential.getSelectedAccountName()));
mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(senderAccount)); // send to yourself
// Convert MimeMessage to Message
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mimeMessage.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
message = new com.google.api.services.gmail.model.Message();
message.setRaw(encodedEmail);
} catch (MessagingException | IOException e) {
e.printStackTrace();
return;
}
// Send email
try {
mGmailApiService.users().messages().send("me", message).execute(); // (EmailUtils:397)
// Success, email sent!
} catch (IOException e) {
e.printStackTrace();
// ==== THIS is where users get UserRecoverableAuthIOExceptions ==== //
}
}
With firebase logging I've found out that the crash happens both shortly after authentication as well long after. I can also see that it sometimes happens that the code sends one email successfully and then crashes on the next one right after. I also get quite a few reports of SocketTimeoutException which I believe are caused by slow/faulty internet connection though.
Thank you for your time.
EDIT:
The only way I am able to reproduce the error is by manually removing my app from the list of "Third-party apps with account access". But I don't see why this should happen without user interaction.

Using SharedPreferences data in Application class

I am developing an app and I use Socket.io on it, I initialize the socket in a class that extends Application and looks like this:
public class Inicio extends Application{
private Socket mSocket;
private SharedPreferences spref;
#Override
public void onCreate(){
super.onCreate();
try{
spref = getSharedPreferences("accountData", Context.MODE_PRIVATE);
IO.Options op = new IO.Options();
op.forceNew = true;
op.reconnection = true;
op.query = "tok=" + spref.getString("sessiontoken", "") + "&usr=" + spref.getString("userid", "");
mSocket = IO.socket(Constants.serverAddress, op);
}catch(URISyntaxException e){
throw new RuntimeException(e);
}
}
public Socket getmSocket(){
return mSocket;
}
}
So I can get and use the same socket instance in other parts of my application's code calling the following way:
Inicio appClass = (Inicio) getApplication();
mSocket = appClas.getmSocket();
mSocket.connect();
But there is a small problem that motivated me to post this question, can you see when I call to SharedPreferences in the Application class? I do this because I need to send the session token and user account ID to properly start the socket connection with my server, the problem is:
Imagine that a user opens the app for the first time and does not have an account yet, he will login or register and then the session token and user ID will be saved to SharedPreferences, but when the app started and ran the Application class, SharedPreferences was still empty and did not have the required token and user ID to establish the connection, so the user would have to reopen the app now to be able to use the socket successfully.
So I ask you: What are my alternative options for solving the problem? Is there another structure besides the Application class that I could use to not suffer from this problem? Or is there some way to bypass this problem?
What I'm doing to get around the problem for now is to restart the app programmatically when login occurs but I believe this is looks like a sad joke and not the ideal way to do it.
Thanks, I apologize for this long question of mine, but I'll be grateful for any help.
Separate your soket creation logic like below:
private void createSoket() {
spref = getSharedPreferences("accountData", Context.MODE_PRIVATE);
String sessiontoken = spref.getString("sessiontoken", "");
String userId = spref.getString("userid", "");
if(!(TextUtils.isEmpty(sessiontoken) || TextUtils.isEmpty(userId))) {
try {
IO.Options op = new IO.Options();
op.forceNew = true;
op.reconnection = true;
op.query = "tok=" + sessiontoken + "&usr=" + userId;
mSocket = IO.socket(Constants.serverAddress, op);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
And when required soket check null and create before pass the instance.
public Socket getmSocket(){
if(mSoket == null)
createSoket();
return mSocket;
}
N.B: Without valid settionToken and userId, soket is null
This is complete Application class:
public class Inicio extends Application{
private Socket mSocket;
private SharedPreferences spref;
#Override
public void onCreate(){
super.onCreate();
createSoket();
}
private void createSoket() {
spref = getSharedPreferences("accountData", Context.MODE_PRIVATE);
String sessiontoken = spref.getString("sessiontoken", "");
String userId = spref.getString("userid", "");
if(!(TextUtils.isEmpty(sessiontoken) || TextUtils.isEmpty(userId))) {
try {
IO.Options op = new IO.Options();
op.forceNew = true;
op.reconnection = true;
op.query = "tok=" + sessiontoken + "&usr=" + userId;
mSocket = IO.socket(Constants.serverAddress, op);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
public Socket getmSocket(){
if(mSoket == null)
createSoket();
return mSocket;
}
}

How to schedule a java code having messageArrived method of MqttCallback

I am new in MQTT world. I have written a code to subscribe a topic and get message from topic and store it in database. Now my problem is how to put this code on server so that it will keep receiving message infinitely. I am trying to create a scheduler but in that case i am Getting Persistence Already in Use error from MQTT. I cannot change the clientId every time it connect. It is a fixed one in my case. Is there any way to get the persistence object which is already connected for a particular clientId?
Please help. Thanks and advance.
Please Find the code subscribe topic and messageArrived method of mqqt to get message from topic
public class AppTest {
private MqttHandler handler;
public void doApp() {
// Read properties from the conf file
Properties props = MqttUtil.readProperties("MyData/app.conf");
String org = props.getProperty("org");
String id = props.getProperty("appid");
String authmethod = props.getProperty("key");
String authtoken = props.getProperty("token");
// isSSL property
String sslStr = props.getProperty("isSSL");
boolean isSSL = false;
if (sslStr.equals("T")) {
isSSL = true;
}
// Format: a:<orgid>:<app-id>
String clientId = "a:" + org + ":" + id;
String serverHost = org + MqttUtil.SERVER_SUFFIX;
handler = new AppMqttHandler();
handler.connect(serverHost, clientId, authmethod, authtoken, isSSL);
// Subscribe Device Events
// iot-2/type/<type-id>/id/<device-id>/evt/<event-id>/fmt/<format-id>
handler.subscribe("iot-2/type/" + MqttUtil.DEFAULT_DEVICE_TYPE
+ "/id/+/evt/" + MqttUtil.DEFAULT_EVENT_ID + "/fmt/json", 0);
}
/**
* This class implements as the application MqttHandler
*
*/
private class AppMqttHandler extends MqttHandler {
// Pattern to check whether the events comes from a device for an event
Pattern pattern = Pattern.compile("iot-2/type/"
+ MqttUtil.DEFAULT_DEVICE_TYPE + "/id/(.+)/evt/"
+ MqttUtil.DEFAULT_EVENT_ID + "/fmt/json");
DatabaseHelper dbHelper = new DatabaseHelper();
/**
* Once a subscribed message is received
*/
#Override
public void messageArrived(String topic, MqttMessage mqttMessage)
throws Exception {
super.messageArrived(topic, mqttMessage);
Matcher matcher = pattern.matcher(topic);
if (matcher.matches()) {
String payload = new String(mqttMessage.getPayload());
// Parse the payload in Json Format
JSONObject contObj = new JSONObject(payload);
System.out
.println("jsonObject arrived in AppTest : " + contObj);
// Call method to insert data in database
dbHelper.insertIntoDB(contObj);
}
}
}
Code to connect to client
public void connect(String serverHost, String clientId, String authmethod,
String authtoken, boolean isSSL) {
// check if client is already connected
if (!isMqttConnected()) {
String connectionUri = null;
//tcp://<org-id>.messaging.internetofthings.ibmcloud.com:1883
//ssl://<org-id>.messaging.internetofthings.ibmcloud.com:8883
if (isSSL) {
connectionUri = "ssl://" + serverHost + ":" + DEFAULT_SSL_PORT;
} else {
connectionUri = "tcp://" + serverHost + ":" + DEFAULT_TCP_PORT;
}
if (client != null) {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
client = null;
}
try {
client = new MqttClient(connectionUri, clientId);
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(this);
// create MqttConnectOptions and set the clean session flag
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(authmethod);
options.setPassword(authtoken.toCharArray());
//If SSL is used, do not forget to use TLSv1.2
if (isSSL) {
java.util.Properties sslClientProps = new java.util.Properties();
sslClientProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
options.setSSLProperties(sslClientProps);
}
try {
// connect
client.connect(options);
System.out.println("Connected to " + connectionUri);
} catch (MqttException e) {
e.printStackTrace();
}
}
}

usb4java USB error 4: Unable to open USB device:

I am attempting to interface with the PS3's DS3 controller. I have managed to do so in C# using an implementation of libusb but decided to move my implementation to java. Unfortunately my move to java has not been so smooth. The device seems to be found in the device list but when I attempt to open it I get the following error " USB error 4: Unable to open USB device: No such device (it may have been disconnected)"
public class Main {
private static final short VID = 0x054c;
private static final short PID = 0x0268;
Context context;
public Main() {
context = new Context();
int result = LibUsb.init(context);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to initialize libusb.", result);
}
ByteBuffer data = ByteBuffer.allocate(49);
DeviceHandle ds3Handle = getDeviceHandle(findDevice(VID, PID));
LibUsb.controlTransfer(ds3Handle, (byte)0xa1, (byte)0x1, (short)0x101, (short)0, data, 1000L);
LibUsb.exit(context);
}
private Device findDevice(int vid, int pid) {
Device UsbDevice = null;
DeviceList list = new DeviceList();
int result = LibUsb.getDeviceList(context, list);
if (result < 0) {
throw new LibUsbException("Unable to get device list", result);
}
try {
for(Device device: list) {
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor(device, descriptor);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to read device descriptor", result);
}
if (descriptor.idVendor() == vid && descriptor.idProduct() == pid) {
UsbDevice = device;
System.out.println("found");
}
}
} finally {
LibUsb.freeDeviceList(list, true);
}
return UsbDevice;
}
private DeviceHandle getDeviceHandle(Device device) {
DeviceHandle handle = new DeviceHandle();
int result = LibUsb.open(device, handle);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to open USB device", result);
}
return handle;
}
public static void main(String [] args){
new Main();
}
}
LibUsb.freeDeviceList(list, true);
That true is the problem. "final boolean unrefDevices" is shown in javadoc. Your code is releasing the Device before you have a chance to open it.
Just changing to false it is not enough you also need to call refDevice with the device you need to return
example:
} finally {
// Ensure the allocated device list is freed
LibUsb.freeDeviceList(list, false);
}
if (deviceFound != null) {
// Device found
LibUsb.refDevice(deviceFound);
}
return deviceFound;

Android Service-Activity 2 way communication

in my team's Android application I have a service running from boot which communicates with a 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 the activity bi-directionally: for example I am working on the login activity at the moment and the username and passwords are Strings taken from a text field on the app screen and I have been able to pass them to the service for it to send an authorisation command to the server.
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) {
}
This works as I would have expected. When the server responds with a message saying whether or not the login was sucessful, I need it to pass a message back to the activity so that I can start the main activity if succesful or prompt for re-entry if not.
I tried to use the msg.replyTo field to get the return messenger to send the information back, but when I run the app it force closes with a null pointer exception and I have no idea why this is happening. Here is the code that 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 seems to be coming from the
msg.replyTo.send(m);
line of code in both cases (login succesful and login failed)
Any help to fix this problem would be greatly appreciated :)
As Gregg points out in the comments. You need to set msg.replyTo = messenger; int he place where you send the original message.
An example can be found here: http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
I think you forgot to send response to Login Activity by bundle from Service.
So, i made some changes in Messenger Service
define one global variable and made some changes in Incoming Handler
static final int LOGIN_STATUS = 1;
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 = Message.obtain(null, LOGIN_STATUS);
Scanner s = new Scanner(loginReturn);
s.useDelimiter(",");
String c = s.next();
String status = s.next();
String message = s.next();
if (status.equals("OK")) {
b.putString("responseC",c);
b.putString("responseStatus",status);
b.putString("responseMessage",message)
m.setData(b);
try {
msg.replyTo.send(m);
} catch (RemoteException e) {}
}
else {
/*if something is wrong with username and password you can put
a toast*/
}
break;
Now we have to catch this response in our LoginActivity and
take IncomingHandler in Login Activity also
class IncomingHandler extends Handler{
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case ChatService.LOGIN_STATUS:
String C = msg.getData().getString("responseC");
String Status = msg.getData().getString("responseStatus");
String Message = msg.getData().getString("responseMessage");
//Here is your response in LoginActivity, enjoy!!!
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
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_SATUS,0,0);
try {
b.putString("username", usernameStr);
b.putString("password", passwordStr);
msg.setData(b);
msg.replyTo = mMessenger;
messenger.send(msg);
}
catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
This code is working perfectly, hope it will help you,
Thanks

Categories

Resources