android-studio - BroadcastReceiver 触发更新另一个 Activity
问题描述
我正在尝试将一项功能作为我的 android 应用程序的一部分,其中用户根据他们在地图上的位置与地理围栏进行交互,它会启动一个对话框,告诉用户他们使用 BroadcastReceiver 在路线的起点附近在自己的班级中。
到目前为止,我可以触发它并提供 Toast 消息,但我似乎无法使用它来触发我的其他活动中的 UI 更改。
这是我的 BroadcastReceiver 类-
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
private static final Object TAG = "Error";
@Override
public void onReceive(Context context, Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
Log.d("TOASTY", "onReceive: Geofence even has error..");
}
List<Geofence> triggeredGeofenceList = geofencingEvent.getTriggeringGeofences();
for (Geofence geofence : triggeredGeofenceList) {
Log.d("GEOF", "onReceive: "+geofence.getRequestId());
}
Location triggerLocation = geofencingEvent.getTriggeringLocation();
double lat = triggerLocation.getLatitude();
double lon = triggerLocation.getLongitude();
Toast.makeText(context, "GEOFENCE TRIGGERED AT : LAT IS :" + lat + " LON IS : " +lon, Toast.LENGTH_SHORT).show();
int transitionType = geofencingEvent.getGeofenceTransition();
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
Toast.makeText(context, "Entered Geofence", Toast.LENGTH_SHORT).show();
Log.d("GEOF", "onReceive: "+geofencingEvent.getGeofenceTransition());
break;
case Geofence.GEOFENCE_TRANSITION_DWELL:
Toast.makeText(context, "Dwelling inside of Geofence", Toast.LENGTH_SHORT).show();
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
Toast.makeText(context, "Exited Geofence area", Toast.LENGTH_SHORT).show();
break;
}
Bundle b = intent.getExtras();
Intent i = new Intent(context, routeActivity.class);
i.putExtra("lat", lat);
i.putExtra("lon", lon);
i.putExtras(b);
Log.d("LOLCALLY", "onReceive: "+i);
context.sendBroadcast(i);
}
}
我的想法是使用意图,我试图将触发的位置(我可以在日志输出中看到是正确的)拉到我的其他活动中,但没有任何乐趣。
非常感谢!
解决方案
您需要在您的活动上注册您的接收器并处理其回调:
public class MyActivity extends AppCompatActivity {
private BroadcastReceiver geofenceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Pull triggered location and use it to update the activity
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(geofenceReceiver, new IntentFilter("YOUR_GEOFENCE_ACTION"));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(geofenceReceiver);
}
}
推荐阅读
- python - Getting the column "number" and column name to make it easier to select several - not always adjacent - columns in a large df in pandas
- javafx - 在javafx中绘制箭头形状
- javascript - 是否可以关闭所需的流注释?
- excel - 屏幕更新不会更改为 false
- firebase - 将 Firebase 用户属性更改或删除给特定用户
- c - Non-initialisation of proper array element causes undefined behavior
- elasticsearch - Grok 模式在 Kibana Grok Debbuger 上运行良好,但不适用于 logstash
- c++ - 有没有办法覆盖仅当两个模板参数相同时才匹配的模板方法?
- python - 为 findContours 预处理图像
- php - 缩略图不会自动生成。即使在缩略图文件夹中也不会创建任何内容。我应该怎么办?