Arvi Fox website

Android broadcast receiver

BroadcastReceiver

Message:

  1. global
    mContext.sendBroadcast(mIntent);
    
  2. local
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(mIntent);
    
  3. ordered
    mContext.sendOrderedBroadcast(mIntent, mPermissionStr);
    

Why?

  • to get message from OS
  • to get message from other apps
  • to get message from inner components
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        StringBuilder sb = new StringBuilder();
        sb.append("Action: " + intent.getAction() + "\n");
        sb.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString());
        String log = sb.toString();
        Toast.makeText(context, log, Toast.LENGTH_LONG).show();
    }
}

onReceive lifecycle

  • default in UI thread
  • there is 10 sec to complete

Create

BroadcastReceiver mReceiver = new MyBroadcastReceiver();
IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
mContext.registerReceiver(mReceiver, mfilter);
//foo
mContext.unregisterReceiver(mReceiver, mFilter);

another way

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
  <action android:name="android.intent.action.ACTION_AIRPLANE_MODE_CHANGED" />
    </intent-filter>
</receiver>

Leave a Reply

 

Close Menu