[英]Which object use in Android instead of NotificationCenter in IOS?
iOS使用NotificationCenter的方式如下:
let failureObserver = NSNotificationCenter.defaultCenter().addObserverForName(downloadEndFailureNotificationName, object: nil, queue: nil) { (notification) in
//Process failed result
self._processFailureResultData(forID: connectionID)
}
那么,在Android中使用什么来代替NotificationCenter?
您使用Notification.Builder来构建Notification实例。 如果您正在寻找类似于ios的Observer,请查看Broadcast Receiver
LocalBroadcastManager
是一个非常重量级的解决方案,它反映了对NSNotificationCenter
所做的误解。
工作的最佳工具很可能是Guava的EventBus之类的东西 。 这是使用它的一种简单方法。
[NSNotificationCenter defaultCenter]
等效项。 become , and an becomes a . 在Guava库和下面的描述中,Apple的成为 ,而成为 。 is called a . 发布的对象称为 。 EventBus eventBus = new EventBus();
public class MyCustomEvent {
public MyCustomEvent() {}
}
MyCustomEvent
上注册事件通知。 您需要使用我们在步骤1中创建的事件总线实例。注册过程包括向事件总线注册类的实例。 此类需要一个或多个带有@Subscribe
批注的方法。 这样的方法必须将上面定义的事件类作为唯一的参数。 方法的名称无关紧要。 public class MyConsumerClass {
public MyConsumerClass(EventBus eventBus) {
eventBus.register(new Object() {
@Subscribe
public void receivedCustomEvent(MyCustomEvent event) {
// Do something with the received notification/event.
}
});
}
...
}
eventBus.post(new MyCustomEvent());
有关更多信息,请阅读Guava库。
像NotificationCenter一样,您可以注册和注销对象为观察者。 您可以发送广播消息来模拟iOS通知行为。
有关用法,请参阅此 StackOverflow问题
创建一个Notification.Builder :
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
然后发出通知:
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
向AndroidManifest.xml添加权限
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
公共类GCMBroadcastReceiver扩展了BroadcastReceiver {
private static final String TAG = GCMBroadcastReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
if ("com.google.android.c2dm.intent.REGISTRATION".equals(intent.getAction())) {
// Register Localytics (this will call Localytics.handleRegistration(intent))
new PushReceiver().onReceive(context, intent);
} else if ("com.google.android.c2dm.intent.RECEIVE".equals(intent.getAction())) {
// DO SOMETHING
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.