这是我的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活动,以便接收GCM消息?是否有一种通过编程而不是通过清单文件来完成此操作的方法?
在上一个关于BroadcastRecievers - How do I publish an update to Dashclock when my application receives an Intent?的问题之后,我找到了这个解决方案。
发布于 2013-08-14 19:57:14
如何保持BroadcastReceiver活动,以便接收GCM消息?
在清单中注册它,就像GCM样本向您显示的那样。
是否有一种通过编程而不是通过清单文件来完成此操作的方法?
不是,但您可以通过PackageManager和setComponentEnabledSetting()启用和禁用清单注册接收器.
https://stackoverflow.com/questions/18230141
复制相似问题