如何从处理程序中获取数据

How to get data from handler

在我的 android 项目中,我有 java class 实现了 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() 函数中,我正在获取字符串值,但是如何将该字符串传递给 LensPickerActivity 上下文?。我的意思是主线程。我正在使用处理程序机制,但它对我不起作用。下面是 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:

            }
        }
    };  

在 mHandlerPhone 中,我得到 String is null。如何在主线程中获取字符串值。

谢谢

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:

            }
        }