我只是使用一个简单的逻辑来获取联系人姓名(你们都可以在下面的代码中看到使用 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;
}
最佳答案
AsyncTask#doInBackground()
只有在您对其对象调用 execute()
后才会被调用。这就是它异步工作的方式。它当然会在构造函数之后调用。在 doInBackground
中调试您的代码。
注意:- 您也可以像一些普通的非静态方法一样直接调用 doInBackground()
但这没有任何意义,因为这样它就不会被异步调用。
你的电话应该是:
新的 findContacts ("Alice").execute()
。
类名应该是 FindContacts
而不是 findContacts
( Java naming Conventions )。
关于android - 在异步任务中,构造函数是否首先运行 doInBackground?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905792/