我需要获取用户位置并将该位置的请求发送到服务器。我有一个用于显示服务器数据的recyclerview。为了更新位置,我在主要活动的onStart中使用此代码,并希望在recyclerview的空闲状态下获取位置。现在我不知道如何实现位置监听器。
维护活动:
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 10000, 0, locationListener);
}
和:
public abstract class StoryPaginationScrollListener extends RecyclerView.OnScrollListener{
LinearLayoutManager layoutManager;
LocationListener locationListener;
Context context;
public StoryPaginationScrollListener(LinearLayoutManager layoutManager, LocationListener locationListener, Context context) {
this.layoutManager = layoutManager;
this.locationListener = locationListener;
this.context = context;
}
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == SCROLL_STATE_IDLE){
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
}
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
在这种情况下需要一个位置:if(newState == SCROLL_STATE_IDLE)
,并在loadMoreItems()中使用此位置。
答案 0 :(得分:0)
尝试实施LocationListener
像这样
class MyActivity extends Activity implements LocationsListener{
public Location location
@Override
public void onLocationChanged(Location location) {
this.location = location
}
public void someLogic(){
new RecyclerView.OnScrollListener(){
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == SCROLL_STATE_IDLE){
if(location != null){
//write your code here
}
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
};
}