在将iPhone应用程序移植到android的过程中,我正在寻找在应用程序内进行通信的最佳方式。意图似乎是要走的路,这是最好的(唯一的)选择吗? NSUserDefaults在性能和编码方面似乎比Intents重量轻得多。
我还应该添加我有一个状态的应用程序子类,但我需要让另一个活动知道一个事件。
答案 0 :(得分:322)
我找到的最佳等效词是LocalBroadcastManager,它是Android Support Package的一部分。
从LocalBroadcastManager文档:
帮助程序注册并向您的进程中的本地对象发送Intent广播。与使用sendBroadcast(Intent)发送全局广播相比,这有许多优点:
- 您知道您播放的数据不会离开您的应用,因此无需担心泄露私人数据。
- 其他应用程序无法将这些广播发送到您的应用程序,因此您无需担心他们可以利用安全漏洞。
- 它比通过系统发送全球广播更有效。
使用此功能时,您可以说Intent
等同于NSNotification
。这是一个例子:
监视名为"custom-event-name"
的事件的通知的活动。
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// This is just like [[NSNotificationCenter defaultCenter] addObserver:...]
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
// This is somewhat like [[NSNotificationCenter defaultCenter] removeObserver:name:object:]
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
发送/广播通知的第二个活动。
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Every time a button is clicked, we want to broadcast a notification.
findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
使用上面的代码,每次点击按钮R.id.button_send
时,都会广播一个意图,并由mMessageReceiver
中的ReceiverActivity
收到。
调试输出应如下所示:
01-16 10:35:42.413: D/sender(356): Broadcasting message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message!
答案 1 :(得分:12)
这与@Shiki的答案类似,但是从iOS开发者和通知中心的角度来看。
首先创建某种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<String, String> params) {
Intent intent = new Intent(notification.name());
// insert parameters if needed
for(Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
intent.putExtra(key, value);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
然后,您还需要一些枚举类型来确保使用字符串编码时出错 - (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();
}
}
最后我们将从一些回调或休息服务或其他任何方式向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<String,String> params = new HashMap<String, String>();
params.put("isSuccess", String.valueOf(false));
NotificationCenter.postNotification(context, NotificationType.LoginResponse, params);
}
就是这样,欢呼!
答案 2 :(得分:6)
答案 3 :(得分:4)
你可以使用这个:http://developer.android.com/reference/android/content/BroadcastReceiver.html,它会产生类似的行为。
您可以通过Context.registerReceiver(BroadcastReceiver,IntentFilter)以编程方式注册接收器,它将捕获通过Context.sendBroadcast(Intent)发送的意图。
但请注意,如果接收方的活动(上下文)已暂停,则接收方将不会收到通知。
答案 4 :(得分:4)
我发现使用Guava lib的EventBus是组件之间发布 - 订阅式通信的最简单方式,而不需要组件明确地相互注册
在https://code.google.com/p/guava-libraries/wiki/EventBusExplained
上查看他们的样本// Class is typically registered by the container.
class EventBusChangeRecorder {
@Subscribe public void recordCustomerChange(ChangeEvent e) {
recordChange(e.getChange());
}
// somewhere during initialization
eventBus.register(this);
}
// much later
public void changeCustomer() {
eventBus.post(new ChangeEvent("bla bla") );
}
您可以通过在build.gradle中添加依赖项来简单地在Android Studio上添加此lib:
compile 'com.google.guava:guava:17.0'
答案 5 :(得分:0)
您可以使用弱引用。
通过这种方式,您可以自己管理内存并随意添加和删除观察者。
当addObserver添加这些参数时 - 将您要添加的活动中的上下文强制转换为空接口,添加通知名称,并调用方法来运行接口。
运行接口的方法有一个名为run的函数,用于返回传递此类内容的数据
public static interface Themethodtorun {
void run(String notification_name, Object additional_data);
}
创建一个观察类,该类调用具有空接口的引用。 还要从addobserver中传递的上下文构建Themethodtorun接口。
将观察结果添加到数据结构中。
要调用它将是相同的方法,但您需要做的就是在数据结构中找到特定的通知名称,使用Themethodtorun.run(notification_name,data)。
这会将回调发送到您创建具有特定通知名称的观察者的位置。 完成后不要忘记删除它们!
这是弱参考的好参考。
http://learningviacode.blogspot.co.nz/2014/02/weak-references-in-java.html
我正在将此代码上传到github。睁大眼睛!
答案 6 :(得分:0)
Kotlin :这是Kotlin中的@Shiki版本,但是如何通过一些重构使其成为片段。
Fragment.kt
class MyFragment : Fragment() {
private var mContext: Context? = null
private val mMessageReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
//Do something here after you get the notification
myViewModel.reloadData()
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onDestroy() {
LocalBroadcastManager.getInstance(mContext!!).unregisterReceiver(mMessageReceiver)
super.onDestroy()
}
private fun registerCallSheetUpdate() {
LocalBroadcastManager.getInstance(mContext!!).registerReceiver(mMessageReceiver, IntentFilter(Constant.NOTIFICATION_SOMETHING_HAPPEN))
}
}
在任何地方发布通知。只有您需要上下文。
LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(Constant.NOTIFICATION_SOMETHING_HAPPEN))```
PS :
object Constant {
const val NOTIFICATION_CALL_SHEET_LIST_UPDATED_LOCALLY = "notification_something_happened_locally"
}
activity
(类似null
)或conext
来使用。答案 7 :(得分:0)
我写了一个可以完成相同工作的包装器,相当于使用LiveData的iOS
包装器:
class ObserverNotify {
private val liveData = MutableLiveData<Nothing>()
fun postNotification() {
GlobalScope.launch {
withContext(Dispatchers.Main) {
liveData.value = liveData.value
}
}
}
fun observeForever(observer: () -> Unit) {
liveData.observeForever { observer() }
}
fun observe(owner: LifecycleOwner, observer: () -> Unit) {
liveData.observe(owner) { observer()}
}
}
class ObserverNotifyWithData<T> {
private val liveData = MutableLiveData<T>()
fun postNotification(data: T) {
GlobalScope.launch {
withContext(Dispatchers.Main) {
liveData.value = data
}
}
}
fun observeForever(observer: (T) -> Unit) {
liveData.observeForever { observer(it) }
}
fun observe(owner: LifecycleOwner, observer: (T) -> Unit) {
liveData.observe(owner) { observer(it) }
}
}
声明观察者类型:
object ObserverCenter {
val moveMusicToBeTheNextOne: ObserverNotifyWithData<Music> by lazy { ObserverNotifyWithData() }
val playNextMusic: ObserverNotify by lazy { ObserverNotify() }
val newFCMTokenDidHandle: ObserverNotifyWithData<String?> by lazy { ObserverNotifyWithData() }
}
在观察活动中:
ObserverCenter.newFCMTokenDidHandle.observe(this) {
// Do stuff
}
通知:
ObserverCenter.playNextMusic.postNotification()
ObserverCenter.newFCMTokenDidHandle.postNotification("MyData")