这是我的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?
答案 0 :(得分:1)
如何保持BroadcastReceiver处于活动状态以便我可以接收GCM消息?
在清单中注册它,就像GCM样本显示的那样。
有没有办法以编程方式完成此操作,而不是通过清单文件?
不,但您可以通过PackageManager
和setComponentEnabledSetting()
启用和停用清单注册的接收器。