简体   繁体   English

Android:从 UI 线程启动工作线程挂起应用程序

[英]Android: start a worker thread from UI thread hang the application

I have written below codes.我写了下面的代码。 Every time I run it, Application stops.每次我运行它时,应用程序都会停止。 Could you help me with any any idea?你能帮我任何想法吗?

If I don't start the worker thread, the code was okay.如果我不启动工作线程,代码就可以了。 My question is:我的问题是:

Can I start a worker thread from onCreate function on the UI thread?我可以从 UI 线程上的onCreate function 启动工作线程吗?

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private Bluetooth mBluetooth = null;
    private Gauge mGauge;
    private Obd2 mObd2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        android.support.v7.widget.Toolbar myToolbar = findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        mGauge = findViewById(R.id.gauge1);
        mGauge.setValue(120);
        mBluetooth = new Bluetooth();
        try {
            mBluetooth.connect();
        } catch (IOException e) {
        }
        mObd2 = new Obd2(mBluetooth);
        mObd2.command(obd2CommandEnum.RESET);

        runRPMThread();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    private void runRPMThread() {

        new Thread() {
            public void run() {
                while (true) {
                    try {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                mGauge.setValue(mObd2.rpm());
                            }
                        });
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}

Just debugged into the issue...there was a null pointer in mObd2.rpm() function.刚刚调试到问题...在 mObd2.rpm() function 中有一个 null 指针。 I need to run the application with a connection to my car with bluetooth.我需要通过蓝牙连接到我的汽车来运行应用程序。 without that, I have a null pointer...没有那个,我有一个 null 指针......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM