android - 在异步任务中,构造函数是否首先运行 doInBackground?

标签 android android-asynctask

我只是使用一个简单的逻辑来获取联系人姓名(你们都可以在下面的代码中看到使用 if 语句)。但是 if 语句不起作用。问题是我正在比较字符串 s1,它是联系人用 s2 命名,我从构造函数中获取它,我非常有信心 s1 包含与 s2 相同的内容。所以它首先运行构造函数或在后台执行?因为如果 doInBackground 那么我需要将参数设置为全局参数而不是传递在这个方法中。

private class findContacts extends AsyncTask<Void, String, String> {
    String contactName;
    public findContacts(String contactName) {
        this.contactName = contactName;
    }

    @Override
    protected String doInBackground(Void... voids) {

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                null,
                null,
                null);

        String name = null,phoneNumber=null;

        if (phones != null) {
            while (phones.moveToNext())
            {
                name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));



                System.out.println("1st name "+name.toLowerCase()+" 2nd name"+contactName.toLowerCase()+" both are same ?"+name.toLowerCase().contains(contactName.toLowerCase()));

                if (name.toLowerCase().equals(contactName.toLowerCase())){   // The problem lies here 
                    System.out.println(name+" "+phoneNumber);
                    phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }else {
                   // newPhoneNum="123456";
                }

            }

            phones.close();
        }
        return phoneNumber;

    }

enter image description here

最佳答案

AsyncTask#doInBackground() 只有在您对其对象调用 execute() 后才会被调用。这就是它异步工作的方式。它当然会在构造函数之后调用。在 doInBackground 中调试您的代码。

注意:- 您也可以像一些普通的非静态方法一样直接调用 doInBackground() 但这没有任何意义,因为这样它就不会被异步调用。 你的电话应该是:

新的 findContacts ("Alice").execute()

类名应该是 FindContacts 而不是 findContacts( Java naming Conventions )。

关于android - 在异步任务中,构造函数是否首先运行 doInBackground?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905792/

相关文章:

android - 为什么我使用 AsyncTask 时会出现 android.os.NetworkOnMainThreadException?

java - 我无法从 AsyncTask 获得结果?

android - 在 AsyncTask 中启动 Activity 从 Activity 传递上下文

java - Android AsyncTask 订单服务器连接

android - setmargin 在 android 中的相对布局中不起作用

android - 如何在TextView中创建垂直对齐的上标和下标

javascript - 有没有办法用ajax读写mysql数据库?

android - webview-window.getselection() 值即将变为 null

Nativescript 中的 Android 地理围栏。后台事件导致 java.lang.RuntimeException : Unable to instantiate receiver

java - 从内部 AsyncTask 类获取 Arraylist