这里有一些类似于@Shiki的答案,但是从iOS开发者和通知中心的angular度来看。
首先创build一些NotificationCenter服务:
public class NotificationCenter { public static void addObserver(Context context, NotificationType notification, BroadcastReceiver responseHandler) { LocalBroadcastManager.getInstance(context).registerReceiver(responseHandler, new IntentFilter(notification.name())); } public static void removeObserver(Context context, BroadcastReceiver responseHandler) { LocalBroadcastManager.getInstance(context).unregisterReceiver(responseHandler); } public static void postNotification(Context context, NotificationType notification, HashMap params) { Intent intent = new Intent(notification.name()); // insert parameters if needed for(Map.Entry entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); intent.putExtra(key, value); } LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } }
然后,你还需要一些枚举types来保证string编码时的错误 – (NotificationType):
public enum NotificationType { LoginResponse; // Others }
这里是使用(添加/删除观察者)例如在活动中:
public class LoginActivity extends AppCompatActivity{ private BroadcastReceiver loginResponseReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // do what you need to do with parameters that you sent with notification //here is example how to get parameter "isSuccess" that is sent with notification Boolean result = Boolean.valueOf(intent.getStringExtra("isSuccess")); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //subscribe to notifications listener in onCreate of activity NotificationCenter.addObserver(this, NotificationType.LoginResponse, loginResponseReceiver); } @Override protected void onDestroy() { // Don't forget to unsubscribe from notifications listener NotificationCenter.removeObserver(this, loginResponseReceiver); super.onDestroy(); } }
最后是我们如何通过一些callback或rest服务或其他方式向NotificationCenter发送通知:
public void loginService(final Context context, String username, String password) { //do some async work, or rest call etc. //... //on response, when we want to trigger and send notification that our job is finished HashMap params = new HashMap(); params.put("isSuccess", String.valueOf(false)); NotificationCenter.postNotification(context, NotificationType.LoginResponse, params); }
就是这样,欢呼!