我在第二次运行后收到消息"Only the original thread that created a view hierarchy can touch its views."



有一个非常特殊的问题,我读了所有关于android多线程的帖子,但仍然去了著名的错误。但是,我在同一线程的第二次运行后进入,例如源代码中的"thGetDevice";

希望你能帮助我…非常感谢. .

Im/**变量定义*/复选框cbBlueTooth;BluetoothAdapter mBluetoothAdapter;AlertDialog。生成器对话框;ArrayAdapter mArrayAdapter;ListView MainListView;ProgressBar prProgressbar;线程thGetDevices;线程thClearDevices;处理程序处理程序;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* Initial Handler */
    handler=new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(final Message msg) {
                /******************************
                 * 
                 * this line cuse to the trouble
                 */
                BlueQuickActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        // TODO Auto-generated method stub
                        prProgressbar.incrementProgressBy(msg.arg1);
                        mArrayAdapter = (ArrayAdapter<String>)msg.obj;
                        mArrayAdapter.notifyDataSetInvalidated();
                        mArrayAdapter.notifyDataSetChanged();
                        prProgressbar.setVisibility(ProgressBar.INVISIBLE);
                        setListAdapter(mArrayAdapter);
                    }
                });
        }
      };

    /* Set Finalization true */
   // System.runFinalizersOnExit(true);
    setContentView(R.layout.main);

    /* ListView Definition */
    TextView tvHeader = new TextView(this);
    MainListView =  this.getListView();
    MainListView.addHeaderView(tvHeader);
    mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
    //mArrayAdapter.setNotifyOnChange(true);
    prProgressbar = (ProgressBar)findViewById(R.id.progressBar1);
    prProgressbar.setVisibility(ProgressBar.INVISIBLE);

    /* Get Bluetooth driver */
    cbBlueTooth = (CheckBox)findViewById(R.id.cbTurnBlueTooth);
    dialog = new AlertDialog.Builder(this);
    /* initializing Bluetooth adapter **/
    mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        /*ShowNotifMessage("Sorry..", "You Don't have Bluetooth Driver");
        try {
            Thread.sleep(3000);
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }
    // Initial the thGetDeviceThread and thClearDevices
    //initGetDevicesThread();
    //initClearDevicesThread();
    /*Listener for Checkbox*/
    cbBlueTooth.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
             if (isChecked && !mBluetoothAdapter.isEnabled()) {
                 prProgressbar.setVisibility(ProgressBar.VISIBLE);
                 buttonView.setEnabled(false);
                 BluetoothAdapter.getDefaultAdapter().enable();
                 initGetDevicesThread();
                 buttonView.setEnabled(true);
                }
             else if (!isChecked && mBluetoothAdapter.isEnabled()) {
                 prProgressbar.setVisibility(ProgressBar.VISIBLE);
                 buttonView.setEnabled(false);
                 BluetoothAdapter.getDefaultAdapter().disable();
                 initClearDevicesThread();  
                 buttonView.setEnabled(true);
                }
             else
             {
                 prProgressbar.setVisibility(ProgressBar.VISIBLE);
                 buttonView.setEnabled(false);
                 BluetoothAdapter.getDefaultAdapter().enable();
                 initGetDevicesThread();
                 buttonView.setEnabled(true);
             }
        }
    });
}
/** Gets all paird devices and put them in the Listview */
private void initGetDevicesThread()
{
 thGetDevices = new Thread(new Runnable() {
        public void run() {
            Message msg = handler.obtainMessage();
            msg.what = 1;
            msg.obj = getDeviceList();
            handler.sendMessage(msg);
        }
    });
 (thGetDevices).start();
}
/** clear all paird devices and put them in the Listview */
private void initClearDevicesThread()
{
 thClearDevices = new Thread(new Runnable() {
        public void run() {
            Message msg = handler.obtainMessage();
            msg.what = 2;
            msg.obj = clearListOfDevices();
            handler.sendMessage(msg);
        }
    });
 (thClearDevices).start();
}
public ArrayAdapter<String> getDeviceList()
{
    while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_ON);
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            // Add the name and address to an array adapter to show in a ListView
            mArrayAdapter.add(device.getName());
        }
    }
    return mArrayAdapter;
}
private ArrayAdapter<String> clearListOfDevices()
{
    while(BluetoothAdapter.getDefaultAdapter().getState() != BluetoothAdapter.STATE_OFF);
    mArrayAdapter = new ArrayAdapter<String>(MainListView.getContext(), android.R.layout.simple_list_item_1);
    return mArrayAdapter;
}

//** */
private void ShowNotifMessage(String strTitle,String strMsg)
{
    dialog.setTitle(strTitle);
    dialog.setMessage(strMsg);
    dialog.show();
}

}

不能从非UI线程更新UI。要做到这一点,你必须使用runOnUiThread()。把你用来更新UI的代码放在runOnUiThread()里面。

Activity_name.this.runOnUiThread(new Runnable() {
            public void run() {
                prProgressbar.incrementProgressBy(msg.arg1);
        mArrayAdapter = (ArrayAdapter<String>)msg.obj;
        mArrayAdapter.notifyDataSetInvalidated();
        mArrayAdapter.notifyDataSetChanged();
        prProgressbar.setVisibility(ProgressBar.INVISIBLE);
        setListAdapter(mArrayAdapter);
    }
        });

尝试使用下面的Handler

Handler viewUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                ~~~~your code~~~
                break;
            }
        }
    };

相关内容

最新更新