Android 發送廣播簡易工具類
/*** 發送廣播簡易工具類 * Created by Liam on 2015/4/2. */ public class BroadcastUtil { /** * 構造函數設為private,防止外部實例化 */ private void BroadcastManager() { } /** * 注冊廣播接收器 * * @param ctx Context(不可空) * @param iReceiver IReceiver(不可空) * @param action Intent.Action(不可空) */ public static void registerReceiver(Context ctx, final IReceiver iReceiver, final String action) { if (ctx == null || iReceiver == null || action == null) throw new IllegalArgumentException("使用registerReceiver()注冊廣播時,參數Context、IReceiver和Action不能為空!"); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { iReceiver.onReceive(context, intent); } }; IntentFilter filter = new IntentFilter(action); ctx.registerReceiver(receiver, filter); } /** * 發送廣播 * * @param ctx Context(不可空) * @param i Intent(可為null),不需要設置Action,請把Action作為參數傳入 * @param action Intent.Action(不可空) */ public static void send(Context ctx, Intent i, final String action) { if (ctx == null || action == null) throw new IllegalArgumentException("使用send()發送廣播時,參數Context和Action不能為空!"); if (i == null) i = new Intent(); i.setAction(action); ctx.sendBroadcast(i); } /** * 接收廣播的頁面需要實現,把接收后的操作覆寫在OnReceive()方法里 */ public interface IReceiver { void onReceive(Context ctx, Intent intent); } } </pre>
本文由用戶 b77m 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!