Pratibha Patil Pratibha Patil - 13 days ago 7
Android Question

How to get data from handler

In my android project I have java class that implements IUSBDeviceObserver interface.

public class LensPickerActivity extends CarActivity
implements LensPickerSelectionHandler,IUSBDeviceObserver{

private Context mContext;
private PackageManager mPackageManager;
private PagedListView mPagedListView;
MediaReceiver mediaReceiver;
private String mDeviceName = "";
private static final int UPDATE_USB_NAME = 1

public LensPickerActivity(Proxy proxy, Context context, Car car) {
super(proxy, context, car);

mContext = context;
mPackageManager = mContext.getPackageManager();
mSharedPrefs = LensPickerUtils.getFacetSharedPrefs(mContext);


}

// override function from IUSBDeviceObserver
@Override
public void onUSBDeviceChanged(String device) {

mDeviceName = device;
Log.d(TAG,"device name ++++"+" "+mDeviceName);
getAttachedDeviceName(mDeviceName);

}
}


In onUSBDeviceChanged() function I am getting String value but How pass that string to LensPickerActivity context ?. I mean main thread. I am using Handler mechanisam but it is not working for me. below is Hanlder class

private void getAttachedDeviceName(String deviceName) {
Message message = mHandlerPhone.obtainMessage(UPDATE_USB_NAME);
if (deviceName == null) return;
message.obj = deviceName;
Log.d(TAG, "aTTCHEDdEVICE Name :: " + deviceName);
mHandlerPhone.sendMessage(message);
}

Handler mHandlerPhone = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_USB_NAME:
String aResponse = msg.getData().getString("message");
Log.d(TAG, "aTTCHEDdEVICE Name handler :: " + aResponse);
break;
default:

}
}
};


In mHandlerPhone I am getting String is null. How get String value in Main thread.

Thanks

Answer

msg.obj contains your String, so try to use:

Handler mHandlerPhone = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_USB_NAME:
                    String aResponse = (String) msg.obj;
                    Log.d(TAG, "aTTCHEDdEVICE Name handler :: " + aResponse);
                   break;
                default:

            }
        }
Comments