BroadcastReceiver 触发更新另一个 Activity

BroadcastReceiver triggered to update another Activity

我正在尝试将一项功能作为我的 android 应用程序的一部分,用户可以根据他们在地图上的位置与地理围栏进行交互,它会启动一个对话框,告诉用户他们就在附近在自己的 class.

中使用 BroadcastReceiver 的路由起点

到目前为止,我可以触发它并提供 Toast 消息,但我似乎无法使用它来触发我的其他 activity.

中的 UI 更改

这是我的 BroadcastReceiver class -

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


    }

}

我的想法是使用意图,我试图将触发位置(我在日志输出中看到它是正确的)拉到我的另一个 activity 但没有成功。

非常感谢!

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

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