首页 > 解决方案 > 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);


    }

}

我的想法是使用意图,我试图将触发的位置(我可以在日志输出中看到是正确的)拉到我的其他活动中,但没有任何乐趣。

非常感谢!

标签: android-studiobroadcastreceiverandroid-geofence

解决方案


您需要在您的活动上注册您的接收器并处理其回调:

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);
    }
}

推荐阅读