简体   繁体   English

在Android中使用哪个对象而不是IOS中的NotificationCenter?

[英]Which object use in Android instead of NotificationCenter in IOS?

IOS use NotificationCenter likes below: iOS使用NotificationCenter的方式如下:

    let failureObserver =    NSNotificationCenter.defaultCenter().addObserverForName(downloadEndFailureNotificationName, object: nil, queue: nil) { (notification) in

        //Process failed result
        self._processFailureResultData(forID: connectionID)

    }

So, what is using instead of NotificationCenter in Android? 那么,在Android中使用什么来代替NotificationCenter?

You use Notification.Builder to build Notification instance. 您使用Notification.Builder来构建Notification实例。 If you are looking for Observer similar to ios, look into Broadcast Receiver 如果您正在寻找类似于ios的Observer,请查看Broadcast Receiver

LocalBroadcastManager is a very heavyweight solution which reflects a misunderstanding of what NSNotificationCenter does. LocalBroadcastManager是一个非常重量级的解决方案,它反映了对NSNotificationCenter所做的误解。

The best tool for the job is very likely something like Guava's EventBus . 工作的最佳工具很可能是Guava的EventBus之的东西 Here's a simple way to use it. 这是使用它的一种简单方法。

  1. Create an EventBus instance. 创建一个EventBus实例。 This is the [NSNotificationCenter defaultCenter] equivalent. 这是[NSNotificationCenter defaultCenter]等效项。 In the Guava library and the description below, Apple's notifications become events , and an observer becomes a consumer . 在Guava库和下面的描述中,Apple的通知成为事件 ,而观察者成为使用者 An object that posts an event is called a producer . 发布事件的对象称为生产者
EventBus eventBus = new EventBus();
  1. Create an event type . 创建一个事件类型 This is a Java class of your own design. 这是您自己设计的Java类。 You could have it hold any information you need to pass from the producer to your consumers. 您可以让它保存从生产者传递到消费者所需的任何信息。
public class MyCustomEvent {
  public MyCustomEvent() {}
}
  1. In your consumer class, register for event notifications on MyCustomEvent . 在您的使用者类中,在MyCustomEvent上注册事件通知。 You need to use the event bus instance we created in step 1. The process of registration involves registering an instance of a class with the event bus. 您需要使用我们在步骤1中创建的事件总线实例。注册过程包括向事件总线注册类的实例。 This class needs to have one or more methods annotated with the @Subscribe annotation. 此类需要一个或多个带有@Subscribe批注的方法。 Such a method must take as the only argument the event class you defined above. 这样的方法必须将上面定义的事件类作为唯一的参数。 The name of the method doesn't matter. 方法的名称无关紧要。
public class MyConsumerClass {
  public MyConsumerClass(EventBus eventBus) {
    eventBus.register(new Object() {
      @Subscribe
      public void receivedCustomEvent(MyCustomEvent event) {
        // Do something with the received notification/event.
      }
    });
  }
  ...
}
  1. On the producer side, you can now post notifications (events) that are received by the registered consumers. 在生产者端,您现在可以发布注册消费者收到的通知(事件)。 Make sure you use the same event bus instance defined in step 1, which has your consumers registered with. 确保使用与步骤1中定义的事件总线实例相同的事件,该实例已注册了使用者。
eventBus.post(new MyCustomEvent());

For more information read up on the Guava library. 有关更多信息,请阅读Guava库。

Use LocalBroadcastManager 使用LocalBroadcastManager

Like NotificationCenter you can register and unregister object as observers. 像NotificationCenter一样,您可以注册和注销对象为观察者。 You can send broadcast messages to simulate iOS notifications behaviour. 您可以发送广播消息来模拟iOS通知行为。

For the usage refer to this StackOverflow question 有关用法,请参阅 StackOverflow问题

  1. Create a notification 建立通知

Create a Notification.Builder : 创建一个Notification.Builder

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

Then issue the notification: 然后发出通知:

// 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());
  1. Listen to notification (using GCM permissions) 收听通知(使用GCM权限)

Add permissions into AndroidManifest.xml AndroidManifest.xml添加权限

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>

public class GCMBroadcastReceiver extends BroadcastReceiver { 公共类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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM