【发布时间】:2017-08-08 18:26:59
【问题描述】:
我正在使用 loader 从 Internet 获取数据并使用 GoogleApiClient 来获取用户位置,我将 带有位置的字符串 url 传递给加载器构造函数,onCreateLoader 方法在 onLocationChanged 方法之前调用,将用户位置作为对象
问题是我需要 onLocationChanged 方法首先返回位置,以便能够将正确的 url 传递给 onCreateLoader 方法。那么,有什么方法可以先运行 onLocationChanged 方法或延迟加载器的创建方法
onCreateLoader 代码
@Override
public android.content.Loader<Adhan> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "onCreateLoader invoked query here " + mQueryUrl);
if (mQueryUrl != null) {
return new PrayTimeLoader(getContext(), mQueryUrl);
}
return null;
}
onLocationChanged 代码
@Override
public void onLocationChanged(Location location) {
mLocation = location;
makeQueryUrl();
Log.v(LOG_TAG, "latitude is " + location.getLatitude());
Log.v(LOG_TAG, "Longitude is " + location.getLongitude());
}
makeQueryUrl 代码
private String makeQueryUrl() {
StringBuilder theQuery = new StringBuilder();
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
if (mLocation != null) {
String latitude = Double.toString(mLocation.getLatitude());
String longitude = Double.toString(mLocation.getLongitude());
theQuery.append("http://api.aladhan.com/timings/")
.append(ts)
.append("?latitude=")
.append(latitude)
.append("&longitude=")
.append(longitude)
;
Log.v(LOG_TAG, "our url for today is " + theQuery);
}
mQueryUrl = String.valueOf(theQuery);
return mQueryUrl;
}
日志输出
-
08-08 20:48:19.406 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment: onCreateLoader 在此处调用查询 null
08-08 20:48:19.406 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment: onCreateLoader 在此处调用查询 null
08-08 20:48:19.634 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment: onConnected 调用 true
08-08 20:48:19.645 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment: 请求位置
08-08 20:48:19.652 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment:纬度为 30.8567497
08-08 20:48:19.652 25518-25518/com.example.worldwide.wzakerapp V/PrayerFragment:经度为 30.8001775
【问题讨论】:
-
为什么要先调用 onCreateLoader 才能传递它需要的数据(位置)?
-
同一个活动实现了 LocationListener 和 LoaderManager.LoaderCallbacks 所以 onCreateLoader 方法和 onLocationChanged b> 在同一个活动中被覆盖,当我使用日志时,我发现在 onLocationChanged 之前调用了 onCreateLoader 方法。
-
你在哪里初始化加载器?初始化和启动它的触发器应该在 onLocationChanged 之后。以前没有理由这样做。
-
确实你是对的谢谢:)
标签: android android-loadermanager asynctaskloader