我应该在创建通知之前调用WakeLock吗?

时间:2013-04-23 12:18:38

标签: android notifications push-notification google-cloud-messaging wakelock

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

由于

1 个答案:

答案 0 :(得分:8)

我不确定处于待机状态的仿真器是否等同于锁定的设备。如果是,您肯定应该拨打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" />