gpt4 book ai didi

android - 多次调用 onReceive

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:51 26 4
gpt4 key购买 nike

我有一个从其他应用程序获取数据的服务。

当我得到日期时,我会向 broadCast 发送消息以刷新 UI。

多次调用onReceive方法,多次显示数据。

这是我的代码:

DataService.java

if(sizeLat == 1) {

sendMessage("Alerte1;");

}
else {

sendMessage("Alerte2;");
}


private void sendMessage(String message) {
Log.w("","==> send message");
Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

MainActivity.java

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {


Log.e("","Onreceiver");
String message = intent.getStringExtra("message");


if(message.equals("Alerte1")){
parentItems.add(message);
adapter.notifyDataSetChanged();
}}};

@Override
protected void onResume() {
Log.d(TAG, "On Resume");
super.onResume();

// Register mMessageReceiver to receive messages.

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));}

我该如何解决这个问题?

最佳答案

将广播注册行放在 onCreate 中,并在 onDestroy() 方法中取消注册。您必须从 onResume() 移动到 onCreate 的行是:-

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));}

关于android - 多次调用 onReceive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com