Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android中的线程阻塞用户界面_Android_Multithreading_Bluetooth - Fatal编程技术网

android中的线程阻塞用户界面

android中的线程阻塞用户界面,android,multithreading,bluetooth,Android,Multithreading,Bluetooth,我正在使用Android Bluetooth指南中的示例代码,该指南位于“作为客户端连接”下 } 在我的onCreate中,我调用 protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); connectionManager= new ConnectionManager(th

我正在使用Android Bluetooth指南中的示例代码,该指南位于“作为客户端连接”下

}

在我的onCreate中,我调用

protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
    connectionManager= new ConnectionManager(this);
    connectionManager.start();
connectionManager启动一个ConnectThread,该connect thread成功连接到另一个蓝牙设备。但是,直到ConnectThread返回(确切地说,当mmSocket.connect()停止阻塞时),才会呈现布局。
如何首先显示布局

与其从UI线程创建连接管理器,不如在工作线程中创建它,如下所示:

protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
new Thread(new Runnable() {

            @Override
            public void run() {
               connectionManager= new ConnectionManager(YourActivity.this);
               connectionManager.start();
            }
        }).start();
这样你就永远不会阻塞UI线程,希望这对你有所帮助


问候

您可以将其包装到异步任务中

请记住,
setContentView()
只在
onCreate()方法返回后才执行操作。考虑到这一点,您应该在另一个线程而不是UI线程中运行代码

您的代码应该如下所示:

protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
    new Thread(new Runnable() {

            @Override
            public void run() {
               connectionManager= new ConnectionManager(this);
               connectionManager.start();
            }
    }).start();
}

ConnectionManager.start()看起来像什么?如果它直接调用ConnectThread.run(),它将阻止UI线程。您应该调用ConnectThread.start()。
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
    new Thread(new Runnable() {

            @Override
            public void run() {
               connectionManager= new ConnectionManager(this);
               connectionManager.start();
            }
    }).start();
}