【发布时间】:2015-06-26 18:56:02
【问题描述】:
我正在开发一个应用程序,它接收 GCM 通知以提醒用户有关促销和类似的东西。
到目前为止,我已经设法发送和接收通知。这是我的代码:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GCMNotificationIntentService extends IntentService {
public static final int notifyID = 1337;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
sendNotification(extras.getString("type"),extras.getString("msg"));
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String type, String msg) {
Intent resultIntent = new Intent(this, SplashActivity.class);
resultIntent.putExtra("type", type);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("x")
.setContentText(msg)
.setSmallIcon(R.drawable.ic_launcher);
mNotifyBuilder.setContentIntent(resultPendingIntent);
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
mNotifyBuilder.setAutoCancel(true);
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
}
问题是我不知道如何(或在哪里)显示消息警报。
在网上搜索,我发现了一个实现,即使应用程序关闭也会显示消息,但我只需要在应用程序上显示消息,例如:当应用程序打开时或应用程序关闭时然后用户打开它。
【问题讨论】:
标签: android android-intent notifications google-cloud-messaging android-notifications