我有一个主要活动(OceanintelligenceActivity)。在此活动中,我为推送通知注册了设备,还注册了一个接收器,该接收器显示一个对话框并根据从我的服务器发送的信息启动正确的活动。这是我用来注册设备和接收器的代码:
protected void gcmRegistration(){
PMApplication thisApp = PMApplication.getInstance();
AppDelegate delegate = thisApp.getAppDelegate();
final Context context = this;
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
// Let's declare our receiver
registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
Log.d("", "Lets register for Push");
GCMRegistrar.register(this, SENDER_ID);
}else {
if(GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
String apnsToken = delegate.sso.getAPNSToken();
if(!apnsToken.equals(regId)){
Log.d("", "The Device RegId has changed on GCM Servers");
// We should let our servers know about this
ServerUtilities.update(regId, context);
}
} else {
Log.d("","Is not register on PM Server");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
这就是我设置接收器的方式:
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
Log.d("","BroadcastReceiver onReceive");
notificationIntent = GCMIntentService.getNotificationIntent(context);
new AlertDialog.Builder(context)
.setMessage(newMessage+". Would you like to see it right now?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Show update
startActivity(notificationIntent);
}
})
.setNegativeButton("No", null).show();
}
};
GCMIntentService.getNotificationIntent(context)
. 此行返回带有我要启动的 Activity 的 Intent。
每当有通知 onReceive 被调用但对话框仅显示我是否在主要活动中。因此,如果应用程序处于不同的活动中,onReceive
仍然会被调用,但不会显示对话框,因此我无法启动正确的活动。
如何在 BroadcastReceiver 上显示有关当前可见活动的对话框?