如何在设备上设置该屏幕,并在通知到来时振动?

时间:2016-09-08 08:02:14

标签: android android-notifications

您好我正在构建一个我正在使用通知的应用。我希望当收到通知时,我的设备会振动并且如果屏幕处于睡眠模式,那么通知时屏幕会打开。 这是我的通知建设者:

 NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.asp)
                    .setContentText(notificationData.getText())
                    .setContentTitle(notificationData.getTitle())
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setLights(Color.BLUE, 3000, 3000)
                    .setContentIntent(pendingIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(new Random().nextInt(), notification.build());

当收到通知时,我该怎么做才能设置振动和设备的屏幕?

1 个答案:

答案 0 :(得分:2)

在通知构建器上振动设备setVibrate(long[])

    long[] vibrate  = {500,200,200,500};
    notification.setVibrate(vibrate);

要启用设备屏幕,请尝试使用以下代码。

public static void turnScreenOn(int sec, final Context context)
{
        final int seconds = sec;

        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();

        if( !isScreenOn )
        {
        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MyLock");
        wl.acquire(seconds*1000);
        WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyCpuLock");
        wl_cpu.acquire(seconds*1000);
        }
 }

别忘了添加WAKE_LOCK权限。

<uses-permission android:name="android.permission.WAKE_LOCK" />