我通过使用此代码向我的应用程序发送 GCM 消息来创建通知
private static void generateNotification(Context context, int type, String title, String message) {
Intent notificationIntent;
int icon = R.drawable.ic_launcher;
java.util.Random v = new java.util.Random();
int id = v.nextInt(1000);
long when = System.currentTimeMillis();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
notificationIntent = new Intent(context, Home.class);
notificationIntent.putExtra(CommonUtilities.TITLE_ALERT, title);
notificationIntent.putExtra(CommonUtilities.EXTRA_MESSAGE, message);
notificationIntent.putExtra(CommonUtilities.TYPE, type);
notificationIntent.putExtra(CommonUtilities.ID, id);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, type, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
Notification notification_view = notification.setContentTitle(title)
.setContentText(message).setContentIntent(intent)
.setSmallIcon(icon).setWhen(when)
.setVibrate(new long[] { 1000 }).build();
notification_view.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification_view.defaults |= Notification.DEFAULT_SOUND;
// notification_view.sound = Uri.parse("android.resource://" +
// context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification_view.defaults |= Notification.DEFAULT_VIBRATE;
manager.notify(id, notification_view);
}
并使用接收器接收这个待处理的意图
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(!intent.hasExtra(CommonUtilities.TYPE)){
Log.v("msg", "intent vars not received");
return;
}
int type = intent.getExtras().getInt(CommonUtilities.TYPE);
String title = intent.getExtras().getString(CommonUtilities.TITLE_ALERT);
String newMessage = intent.getExtras().getString(CommonUtilities.EXTRA_MESSAGE);
String[] msgArr = newMessage.split(",");
Log.v("message", newMessage);
}
};
但是我的活动没有执行该操作并向我显示日志。我已经使用自定义意图注册了我的接收器
registerReceiver(mHandleMessageReceiver, new IntentFilter(CommonUtilities.DISPLAY_ACTION));
我怎样才能找到错误?
编辑
如果应用程序在前台收到通知,则通知会收到良好但如果活动未运行或已完成并且我在通知上调用它点击什么也没发生