android 多个activity 共用一套广播BroadcastReceiver

「爱情、让人受尽委屈。」 2022-07-24 09:28 283阅读 0赞

public abstract class ParentActivity extends Activity {
public static final String ACTION_1 = “com.example.action1”;
public static final String ACTION_2 = “com.example.action2”;

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) \{
  3. super.onCreate(savedInstanceState);
  4. IntentFilter intentFilter = new IntentFilter();
  5. intentFilter.addAction(ACTION\_1);
  6. intentFilter.addAction(ACTION\_2);
  7. registerReceiver(receiver, intentFilter);
  8. \}
  9. protected abstract void doAction1();
  10. protected abstract void doAction2(String arg);
  11. BroadcastReceiver receiver = new BroadcastReceiver() \{
  12. @Override
  13. public void onReceive(Context context, Intent intent) \{
  14. String action = intent.getAction();
  15. if (action.equals(ACTION\_1)) \{
  16. doAction1();
  17. \} else if (action.equals(ACTION\_2)) \{
  18. String arg = intent.getStringExtra("arg");
  19. doAction2(arg);
  20. \}
  21. \}
  22. \};
  23. @Override
  24. protected void onDestroy() \{
  25. unregisterReceiver(receiver);
  26. super.onDestroy();
  27. \};

}

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android广播BroadcastReceiver

    Android 系统里定义了各种各样的广播,如电池的使用状态,电话的接收和短信的接收,开机启动都会产生一个广播。当然用户也可以自定义自己的广播。 既然说到广播,那么必定有一个