6

我正在向 Android 应用程序添加通知,目前只有模拟器可供测试。当收到通知时,我的 GCMBaseIntentService 子类 (GCMIntentService) 中的 onMessage() 方法将被调用。从这里我创建一个要出现的通知。如果我将模拟器置于待机状态,则看不到任何通知(我不知道它是否会在设备上听到?)。那么我应该在创建通知之前调用 WakeLock 来唤醒设备吗?

谢谢

4

1 回答 1

9

我不确定处于待机状态的模拟器是否等同于锁定设备。如果是,您绝对应该调用 WakeLock,以便即使在设备锁定时也能显示通知。

这是示例代码:

@Override
protected void onMessage(Context context, Intent intent) {
    // Extract the payload from the message
    Bundle extras = intent.getExtras();
    if (extras != null) {
        String message = (String) extras.get("payload");
        String title = (String) extras.get("title");

        // add a notification to status bar
        NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Intent myIntent = new Intent(this,MyActivity.class);
        Notification notification = new Notification(R.drawable.coupon_notification, title, System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
        contentView.setImageViewResource(R.id.image, R.drawable.gcm_notification);
        contentView.setTextViewText(R.id.title, title);
        contentView.setTextViewText(R.id.text, message);
        notification.contentView = contentView;
        notification.contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        mManager.notify(0, notification);
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);
    }
}

当然,您需要将此权限添加到清单中:

<uses-permission android:name="android.permission.WAKE_LOCK" />
于 2013-04-23T15:50:08.237 回答