简体   繁体   English

Android网络和线程

[英]Android Networking and Threading

I have a class that only contains static functions for various database queries. 我有一个只包含用于各种数据库查询的静态函数的类。 Since they are all network-related, I need to execute that code in another thread. 由于它们都是与网络相关的,因此我需要在另一个线程中执行该代码。 I am trying to find the best way to implement this. 我正在尝试找到实现此目的的最佳方法。

public class MyClass {

    public static void someFunction() {
        ...
    }

    public static void anotherFunction() {
        ...
    }

}

I was thinking of doing it this way: 我正在考虑这样做:

public class MyClass {

    public static void someFunction() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ...
            }
        }
    }

    public static void anotherFunction() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ...
            }
        }
    }

}

Or create a new thread when I call these functions: 或在调用这些函数时创建一个新线程:

new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        MyClass.someFunction();
    }
}

new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        MyClass.anotherFunction();
    }
}

Finally, I was wondering if there's a way to run a single thread parallel to the main thread that would exclusively handle these function calls. 最后,我想知道是否有一种方法可以与主线程并行运行一个单独处理这些函数调用的线程。 The main thread would call these functions and the other thread would run them. 主线程将调用这些函数,而另一个线程将运行它们。

Does anyone have any ideas for the best way to implement this? 是否有人对实现此目标的最佳方法有任何想法? Thanks! 谢谢!

Standard Java Concurrency utilities would fit this scenario the best. 标准Java并发实用程序将最适合这种情况。

For example: 例如:

private static final ExecutorService exe = Executors.newSingleThreadExecutor();
...
exe.execute(new Runnable() {
    public void run() {
        ...
        someFunction();
        ...
    }
});

Read about ExecutorService . 了解有关ExecutorService ExecutorService allows you to manage threads as per your requirement. ExecutorService允许您根据需要管理线程。 If you want your threads to spawn sequentially you could simply use ExecutorService ex = Executors.newSingleThreadExecutor() and consequentally add all your threads to this single executorService. 如果希望线程按顺序生成,则可以简单地使用ExecutorService ex = Executors.newSingleThreadExecutor()然后将所有线程添加到此executorService中。

ex.submit(runnableInstance)

However, I've also been at exact same problem which you are facing. 但是,您遇到的问题也完全一样。 I also used threads to query from database. 我还使用线程从数据库查询。 However, it made my code look messy. 但是,这使我的代码看起来很凌乱。 I would recommend you to use queries in main thread if they involve simple operations. 如果它们涉及简单的操作,我建议您在主线程中使用查询。 It hardly brings any lag to app responsiveness. 它几乎不会给应用程序响应带来任何延迟。 That ways, your code would be quite managable. 这样,您的代码将非常易于管理。

EDIT : 编辑:

Long time ago, I also read about CursorLoader class that allows you to run to your queries in background and can be used by implementing LoaderManager.LoaderCallbacks<Cursor> . 很久以前,我还了解了CursorLoader类,该类允许您在后台运行查询,并且可以通过实现LoaderManager.LoaderCallbacks<Cursor>来使用。 That ways, you don't have to write to ugly code to execute every query in background. 这样,您不必编写丑陋的代码即可在后台执行每个查询。 However, to use this you need to wrap your database in a ContentProvider . 但是,要使用此功能,您需要将数据库包装在ContentProvider

I believe easiest solution for you would be to use IntentService 我相信最适合您的解决方案是使用IntentService

Extract from android doc 从android doc提取

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time. 

You just need to process onHandleIntent 您只需要处理onHandleIntent

It does lot of work for you and as it is a subclass of service, you can bound to the service directly or other way (Intent..etc) to get back data. 它为您做了很多工作,并且由于它是服务的子类,因此您可以直接绑定到服务或通过其他方式(Intent..etc)绑定到服务以获取数据。

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

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