Activity update from BroadcastReceiver

This question caused an interesting problem.

The OP has an application that displays a map, and this map must be updated using location markers, which are received via SMS messages. The individual steps are quite simple: SMS messages can be received using BroadcastReceiver, markers can be displayed ItemizedOverlayon top MapView. The hard part is for the receiving part to communicate with the main part of the application.

  • What happens if the application is active MapActivity, and then it BroadcastReceiveris called as a response to an incoming SMS? Is it suspended MapActivitywhile the code BroadcastReceiverruns in the same process? If so, is it safe to BroadcastReceiveraccess MapActivitythrough a static link (which is set using the methodonCreate

  • And vice versa, the application BroadcastReceiveris executed in a separate process and therefore it is necessary to contact the application activity in some other way?

+3
source share
3 answers

Counting the docs, it looks like BroadcastReceiver is running in a different process, I'm not 100% sure ( BroadcastReceiver life cycle )

, BroadcastReceiver ( , onReceive (, Intent)),

, onReceive, , , , .

, Activity BroadcastReceiver, , . , onResume (, ZXing)

 public void onResume(){
    activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    [...]
  }

  public void onPause() {
    [...]
    activity.unregisterReceiver(powerStatusReceiver);
  }

BroadcastReceiver

final class InactivityTimer {

[onResume, onPause, rest of the stuff ...]

    private final class PowerStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent){
          if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            // 0 indicates that we're on battery
            // In Android 2.0+, use BatteryManager.EXTRA_PLUGGED
            int batteryPlugged = intent.getIntExtra("plugged", -1);
            if (batteryPlugged > 0) {
              InactivityTimer.this.cancel();
            }
          }
        }
      }
}

, BroadcastReceiver ( , onReceive). MapActivity , , , .

, , Activity BroadcastReceiver SMS-. , , , .

+4

BroadcastReceiver . BroadcastReceiver . - Activity. Activity , , , Activity . , Intents.

+1

, , , . , , . , .

The public BroadcastReceiver(declared in the manifest and processing android.provider.Telephony.SMS_RECEIVED) should then refer to this intent of the particular application.

0
source

All Articles