android notification center接口,Android相当于NSNotificationCenter

这里有一些类似于@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); }

就是这样,欢呼!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值