这是我的 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");
}
}
正如你所看到的,我BroadcastReceiver
在我的扩展程序初始化时注册了我的 GCM,而在扩展程序被销毁时我正在取消注册它。
只要接收器被初始化,这段代码就可以正常工作,但是 Dashclock 在一段时间不活动后会破坏扩展,因此我无法接收任何 GCM 消息。
如何保持BroadcastReceiver
活动状态以便接收 GCM 消息?有没有办法以编程方式而不是通过清单文件来完成这项工作?
在我的最后一个问题之后,我来到了这个解决方案BroadcastRecievers
——当我的应用程序收到 Intent 时,如何向 Dashclock 发布更新?