在我的android项目中,我有java类,它实现了IUSBDeviceObserver接口。
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);
}
}
在onUSBDeviceChanged()函数中我得到String值但是如何将该字符串传递给LensPickerActivity上下文?我的意思是主线程。我正在使用Handler mechanisam,但它不适合我。以下是Hanlder类
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:
}
}
};
在mHandlerPhone中我得到String为null。如何在主线程中获取String值。
由于
答案 0 :(得分:1)
msg.obj
包含您的String
,因此请尝试使用:
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:
}
}