gpt4 book ai didi

java - 如何在 Dashclock 扩展中维护持久的 BroadcastReceiver?

转载 作者:行者123 更新时间:2023-11-30 11:29:38 26 4
gpt4 key购买 nike

这是我的 Dashclock 扩展的脚手架代码。它从 GCM 接收消息并显示信息。

public class ComputerWidget extends DashClockExtension {

private MessageReceiver objMessageReceiver;
private class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context ctxContext, Intent ittIntent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(ctxContext);
String strType = gcm.getMessageType(ittIntent);
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(strType)) {
showInformation(ittIntent.getExtras());
}
}
}

@Override
protected void onInitialize(boolean booReconnect) {
super.onInitialize(booReconnect);
if (objMessageReceiver != null) {
try {
unregisterReceiver(objMessageReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}

IntentFilter intentFilter = new IntentFilter("com.google.android.c2dm.intent.RECEIVE");
intentFilter.addCategory("com.something.something");
objMessageReceiver = new MessageReceiver();
registerReceiver(objMessageReceiver, intentFilter);
}

public void onCreate() {
super.onCreate();
}

protected void showInformation(Bundle bndBundle) {
final ExtensionData edtInformation = new ExtensionData();
setUpdateWhenScreenOn(true);
try {
if (bndBundle.getString("event").equalsIgnoreCase("logon")) {
edtInformation.visible(true);
edtInformation.expandedTitle(bndBundle.getString("machine"));
edtInformation.expandedBody(getString(R.string.logon, bndBundle.getString("username")));
}
} catch (Exception e) {
edtInformation.visible(false);
}
edtInformation.icon(R.drawable.ic_dashclock);
publishUpdate(edtInformation);
}

public void onDestroy() {
super.onDestroy();
if (objMessageReceiver != null) {
try {
unregisterReceiver(objMessageReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
}

@Override
protected void onUpdateData(int arg0) {
setUpdateWhenScreenOn(true);
System.out.println("Update");
}

}

如您所见,我在初始化扩展时注册我的 GCM BroadcastReceiver,在销毁扩展时注销它。

只要接收器已初始化,这段代码就可以正常工作,但 Dashclock 在一段时间不活动后会破坏扩展,因此我无法接收任何 GCM 消息。

如何让 BroadcastReceiver 保持 Activity 状态以便接收 GCM 消息?有没有办法以编程方式而不是通过 list 文件来完成此操作?

在我最后一个关于 BroadcastRecievers 的问题之后,我想到了这个解决方案 — How do I publish an update to Dashclock when my application receives an Intent?

最佳答案

How can I keep the BroadcastReceiver alive so that I can receive GCM messages?

按照 GCM 示例向您展示的方式在 list 中注册它。

Is there a way to accomplish this programatically and not through the manifest file?

不可以,但您可以通过 PackageManagersetComponentEnabledSetting() 启用和禁用 list 注册接收器。

关于java - 如何在 Dashclock 扩展中维护持久的 BroadcastReceiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18230141/

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