android - 如果 Firebase 中没有内容,则显示警报对话框
问题描述
我有一个应用程序,它获取用户位置并将其发送到我的 Firebase 数据库,该数据库有一个离用户最近的位置列表。定位半径已设置为小于 50 公里(50000 米)。如果该半径内没有位置,我希望出现一个警报对话框,指出没有可用的位置。位置将在应用程序运行时更新。每次用户尝试访问设置半径内的位置时,都应显示警报对话框。有人可以帮助我如何去做吗?任何帮助将不胜感激。
活动
public class LActivity extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Location1";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
public Location mCurrentLocation;
String mLastUpdateTime;
ViewPager viewPager;
ProgressDialog progressdialog;
protected void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Pending");
Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progressdialog.cancel();
}
};
Handler pdcanceller = new Handler();
pdcanceller.postDelayed(progressRunnable,1500);
progressdialog.show();
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_rape_location);
viewPager = (ViewPager) findViewById(R.id.viewpagerL);
viewPager.setAdapter(new RapeLocationPageAdapter(getSupportFragmentManager(),
LActivity.this));
}
public void getLocation(View view) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 501);
} else {
mGoogleApiClient.connect();
}
progressdialog.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 501) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mGoogleApiClient.connect();
} else {
Toast.makeText(this, "Location permission denied. Please grant location permission to the app.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
progressdialog.show();
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
{
final AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setMessage("Location has not been granted");
builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
builder.dismiss();
}
});
builder.show();
return;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
progressdialog.show();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
final AlertDialog builder = new AlertDialog.Builder(this).create();
builder.setMessage("If there are no locations near you, please contact the local police for immediate attention");
builder.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
builder.dismiss();
}
});
builder.show();
}
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
RapeLocation rapeLocation = (RapeLocation) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpagerRape + ":" + viewPager.getCurrentItem());
rapeLocation.update(mCurrentLocation);
}
}
LActivityMain
public class LActivityMain extends Fragment {
RecyclerView recyclerView;
LocationsAdapter locationsAdapter;
ArrayList<LocationModel> locationModelArrayList = new ArrayList<LocationModel>();
ArrayList<LocationModel> filteredlocationModelArrayList = new ArrayList<LocationModel>();
protected DatabaseReference mDatabase;
LActivityMain locationActivityfin;
Button bnt1;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_locationmain, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
locationActivityfin = (LActivityMain) getActivity();
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.rvLocations);
bnt1 = view.findViewById(R.id.locdone);
bnt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
locationsAdapter = new LocationsAdapter(getActivity(), new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
LatLng latLng = new LatLng(filteredlocationModelArrayList.get(position).getLatitude(),
filteredlocationModelArrayList.get(position).getLongitude());
String url = "http://maps.google.com/maps?saddr=" + locationActivityfin.mCurrentLocation.getLatitude() + "," + locationActivityfin.mCurrentLocation.getLongitude() + "&daddr=" + latLng.latitude + "," + latLng.longitude + "&mode=driving";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(url));
PackageManager packageManager = getActivity().getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else {
if (getView() != null)
Snackbar.make(getView(), "Make sure Google Maps is installed to use this feature", Snackbar.LENGTH_LONG).show();
}
}
}, filteredlocationModelArrayList);
getDataFromServer();
//textView.setText(getArguments().getDouble("latitude") + ", " + getArguments().getDouble("longitude"));
}
public void update(Location location) {
// Toast.makeText(getActivity(), "updated", Toast.LENGTH_SHORT).show();
filteredlocationModelArrayList.clear();
for (LocationModel locationModel : locationModelArrayList) {
Location location1 = new Location("Loc");
location1.setLatitude(locationModel.getLatitude());
location1.setLongitude(locationModel.getLongitude());
if (location1.distanceTo(location) <= 50000 && filteredlocationModelArrayList.size() < 30) {
double distance = (double) (location1.distanceTo(location) / 1000);
try {
distance = round(distance, 2);
} catch (Exception e) {
}
locationModel.setDistance(distance);
filteredlocationModelArrayList.add(locationModel);
}
locationsAdapter.update(filteredlocationModelArrayList);
}
}
public double round(double value, int places) {
if (places <= 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
void getDataFromServer() {
mDatabase.child("ali").child("location221").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataChild : dataSnapshot.getChildren()) {
LocationModel locationModel = dataChild.getValue(LocationModel.class);
locationModelArrayList.add(locationModel);
}
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(locationsAdapter);
if (locationActivityRape.mCurrentLocation != null) {
update(locationActivityRape.mCurrentLocation);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
解决方案
假设您已经知道如何判断某个资源与应用程序有一定距离,那么下一个问题是您是否希望它在应用程序的整个生命周期内更新应用程序,或者只是在启动或恢复时更新。
对于前者,作为应用程序初始化的一部分,您会启动某种定时任务。您希望这段代码脱离 UI 线程,它可能需要使用网络来完成它的工作。这个想法是这个任务定期唤醒并执行它需要做的任何事情来检查外部资源。
只要它找到一些有效的资源,它就会重新进入睡眠状态。如果它没有找到有效的资源,那么它会调用回调方法或引发客户端代码监听的意图以显示对话框、响铃等。确保在清理应用程序时关闭此任务,并确保您可以取消运行状态和/或它处理和使用超时。
如果只在启动时触发一个 AsyncTask 得到一些结果,然后通过其 UI 线程处理程序报告(或与调用者通信),那么可以显示一个对话框并且可能关闭应用程序(如果这些资源对应用程序生命周期)。
相关问答:Timertask 或 Handler,AsyncTask Android 示例(但还有许多其他资源。)
推荐阅读
- python - 如何将数组([1,1,1])与数组([2,3,4])相乘以获得数组[[2,3,4],[2,3,4],[2,3,4] ]]?
- csv - backtrader 如何使用分析器访问数据?
- .net-core - 如何验证使用密钥提交的凭据以在 .net 核心中使用 google 登录?
- sql-server - 来自多个表的条件计数?
- java - 是否可以在 Android 中使用共享首选项保存多个 Pdf 文件的最后查看页码?
- python - 将 elasticsearch 快照保存在 s3 的文件夹中
- r - r中“!TRUE + TRUE”的奇怪结果
- matlab - 关于在给定间隔之间找到函数的绝对最大值的Matlab问题
- php - 在我的本地主机中的 laravel 中使用 google smtp 发送验证电子邮件
- ios - 在属性 SwiftUI 中存储 Firebase 侦听器有什么好处?