gpt4 book ai didi

Android广播接收器,每次应用启动时接收广播

转载 作者:行者123 更新时间:2023-11-29 21:31:21 24 4
gpt4 key购买 nike

在我的主要 Activity 中,我绑定(bind)了一个服务。

    //main activity class
public void startNotificationService(){
// add notice service
Context appContext = getApplicationContext();
Intent intent = new Intent(appContext,NotificationService.class);
appContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

当服务被创建时,广播接收器被注册,所以每当 Android 框架发送广播时,服务可以捕获它并推送通知。

    // service class
@Override
public void onCreate() {
handlerMessage = new UnsolicitedMessageHandler();
IntentFilter intentFilter = new IntentFilter("disassociation");
intentFilter.addAction("remediation");
registerReceiver(new UnsolicitedMessageHandler (), intentFilter);
}

下面是广播接收器的句柄类

class UnsolicitedMessageHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String message;
if (action.equals("disassociation")) {
message = intent.getStringExtra("frameName");
showNotification(R.drawable.disconnect,
"Disassocation Notification", message);
}
if (action.equals("remediation")) {
message = intent.getStringExtra("remMsg");
showNotification(R.drawable.scan, "Remediation Notification",
message);
}
}
}

一切正常,问题是每次我终止应用程序并再次启动它时,UnsolicitedMessageHandler 都会收到广播(我知道,系统绝对不会发送广播)这真是令人困惑和沮丧。任何人都可以帮助我吗?提前致谢。

最佳答案

我认为这是因为每当您终止并再次启动您的应用程序时,您都会收到 STICKY 广播。

在 onReceive 中使用 isInitialStickyBroadcast() 检查您正在处理的当前广播是否为 STICKY。如果那是 STICKY 则忽略并且不做任何处理

关于Android广播接收器,每次应用启动时接收广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398343/

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