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

Dar*_*ren 5 notifications android push-notification wakelock google-cloud-messaging

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

谢谢

Era*_*ran 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<uses-permission android:name="android.permission.WAKE_LOCK" />
Run Code Online (Sandbox Code Playgroud)

  • @Darren嗯,在评论中有一些讨论[这里](http://stackoverflow.com/questions/8662339/how-do-i-use-the-constant-full-wake-lock-in-android4- 0). (2认同)