How to turn on screen when new notification is sen

2019-07-21 05:58发布

问题:

This is my code in setting up a notification and it works:

@Override
    public void onReceive(Context context, Intent intent) {

        category = (String) intent.getExtras().get("CATEGORY");
        notes = (String) intent.getExtras().get("NOTES");

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(category).setContentText(notes);

        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);

        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());       
    }

This is a code snippet from my BroadcastReceiver. Whenever this BroadcastReceiver is called it displays a notification in the status bar. During my debugging I noticed that when the screen is turned off and a new notification is made, the screen won't turn on. Is there any way to do this? That whenever a new notification is made and the screen is off, it should be turned on for a duration of time. Simulating like receiving a new sms.

回答1:

try this:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire(3000);
wl.release();


回答2:

Actually, if you only want active the screen when receive a notification, use this code after create the notification:

PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Tag");
wakeLock.acquire();
wakeLock.release();