我收到消息“只有创建视图层次结构的原始线程才能触及其视图。”经过第二次运行

时间:2011-11-12 08:42:33

标签: android multithreading android-listview

hvae非常spcieal问题,我阅读了android中多线程的所有帖子,但仍然出现了famuse错误。但是,我从源代码中的第二次运行“thGetDevice”之后进入了同一个线程;

希望你能帮助我.. thnx ..

我得到了     / **变量定义* /     CheckBox cbBlueTooth;     BluetoothAdapter mBluetoothAdapter;     AlertDialog.Builder对话框;     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();
}

}

2 个答案:

答案 0 :(得分:3)

您无法从非UI线程更新UI。为此,您必须使用runOnUiThread()。将代码更新为runOnUiThread()

内的UI
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);
    }
        });

答案 1 :(得分:0)

尝试使用下面的处理程序

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