如何在主UI线程之外进行编程 [英] How to program outside the main UI thread

查看:90
本文介绍了如何在主UI线程之外进行编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道默认情况下是否存在UI线程,如果不存在,如何创建它,或者如果我在其中,如何告诉它在何处开始和结束(如果存在).如何确定PacketListener不是主UI线程的一部分?

I don't know if a UI thread exists by default, how to create it if not, or how to tell when I'm "in" it where it begins and ends if so. How do I make sure PacketListener isn't part of the main UI thread?

我一直遇到此 NetworkOnMainThreadException .我了解这意味着我正在尝试在主UI线程中执行一些应具有其自己单独线程的操作.但是,我找不到什么可以告诉我如何实际做到的.

I keep running into this NetworkOnMainThreadException. I understand that means that I'm trying to do something in the main UI thread that should have its own separate thread. However, I can't find much to tell me HOW to actually do that.

我曾经以为MainActivity类将是UI线程,因为我有一个UI并可以正常工作.但是,我创建了一个单独的类,该类实现了Runnable,并将网络连接内容放入其中,并且仍然会收到异常,因此它仍然是主线程的一部分,是吗?我可以看到MainActivity没有扩展Thread,所以也许这是一个愚蠢的假设.我没有感觉,如果我添加另一个实现Runnable/extends Thread的类,一切都不会改变.会吗?

I had thought that the MainActivity class would BE the UI thread, since, well, I had a UI and it worked. However, I've created a seperate class that implements Runnable, and put the network connection stuff in there, and am still getting the exception, so it's still part of the main thread, yes? I can see that MainActivity doesn't extend Thread, so maybe that was a dumb assumption. I don't have the feeling that anything will change if I add another class that implements Runnable/extends Thread. Will it?

MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;

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

        listItems = new ArrayList<>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
        ListView listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(adapter);

        (new Thread(new PacketListener(adapter))).run();
    }
}

PackageListener.java:

PackageListener.java:

public class PacketListener implements Runnable {
    ArrayAdapter<String> adapter;

    public PacketListener(ArrayAdapter<String> adapter) {
        this.adapter = adapter;
    }

    public void run() {
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        try {
            DatagramSocket socket = new DatagramSocket();
            socket.receive(packet);
        }
        catch(Exception e) {
            adapter.add("Exception: " + e.toString() );
            e.printStackTrace();
        }
        catch(Error e) {
            adapter.add("Unspecified Error: " + e.toString() );
            e.printStackTrace();
        }
    }
}

我最近的尝试,是尝试遵循此页面的示例,走了我大部分尝试的路线,并彻底破坏了该应用程序. SendAnother是绑定到按钮的测试方法:

My latest attempt, trying to follow this page's example, has gone the route of most of my attempts, and broke the app completely. SendAnother is a testing method bound to a button:

public void sendAnother(View view) {
    adapter.add("button clicked");

    new Thread(new Runnable() {
        public void run() {
            listview.post(new Runnable() {
                public void run() {
                    adapter.add("inside worker thread");
                }
            });
        }
    });
}

我认为接下来我将最终尝试AsyncTask.我不再在乎它是否肮脏".

I think next I'll finally try AsyncTask. I no longer much care if it's "dirty".

推荐答案

ui线程是主线程.您可以通过

ui thread is main thread. you know about current thread by

Thread.currentThread().getName();

对不起,我没有阅读您的全部问题,但是您必须在mainThread之外的另一个线程中进行阻塞处理.

sorry i didn't read your whole question but you have to do blocking proccess in another thread than mainThread.

有很多方法可以做到这一点:AsyncTask,Services,ExecutorService和RxJava. 以及哪种选择取决于您的需求

there are many ways to do that : AsyncTask , Services , ExecutorService and RxJava . and which one to pick depends on your need

此链接会很有帮助:)

这篇关于如何在主UI线程之外进行编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆