Posted on Leave a comment

Android broadcast receiver

BroadcastReceiver

Message:

  1. global

    [code language=”java”]
    mContext.sendBroadcast(mIntent);
    [/code]

  2. local

    [code language=”java”]
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(mIntent);
    [/code]

  3. ordered

    [code language=”java”]
    mContext.sendOrderedBroadcast(mIntent, mPermissionStr);
    [/code]

Why?

  • to get message from OS
  • to get message from other apps
  • to get message from inner components

[code language=”java”]
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();
}
}
[/code]

onReceive lifecycle

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

Create

[code language=”java”]
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);
[/code]

another way

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.