振动推送通知

gui*_*gui 7 android push-notification android-service google-cloud-messaging

首先,我检查了所有这些链接:

但是当我收到推送通知时,我无法实现手机振动.这是我的代码:

PushReceiver

public class PushReceiver extends FirebaseMessagingService {
    public PushReceiver() {
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if(remoteMessage.getData() != null){
            Map<String, String> data = remoteMessage.getData();
            sendNotification(data.get("message"));
        }
        else{
            if(remoteMessage.getNotification() != null) {
                sendNotification(remoteMessage.getNotification().getBody());
            }
        }
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, BaseActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_done_all_24dp)
                .setContentTitle(getString(R.string.str_notification_order_ready))
                .setContentText(messageBody)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        notificationBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        notificationManager.notify(ConstantUtils.NOTIFICATION_ID_ORDER_READY, notificationBuilder.build());
    }
}
Run Code Online (Sandbox Code Playgroud)

允许

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

测试

设备:Nexus 5

Android版本:6.0.1

为了让它发挥作用,我应该做些什么样的未知巫术?

pRa*_*NaY 14

您还可以使用setDefaults (int defaults)您的NotificationCompat.Builder实例,它为您提供默认的系统声音,振动和灯光以供您通知.

该值应该是以下一个或多个字段与按位或(|)结合使用:DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS.

对于所有默认值,请使用DEFAULT_ALL.

防爆.根据你的代码,你设置默认声音,如果你想设置默认声音和振动:

notificationBuilder.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE);
Run Code Online (Sandbox Code Playgroud)

如果您想要所有默认设置,您可以通过设置来实现它notificationBuilder.setDefaults(-1),它将其视为DEFAULT_ALL值.

请参阅android doc for setDefaults.

编辑:

振动延迟1000毫秒.如果您将第一个设置为0,它将立即关闭.这是一种{延迟,振动,睡眠,振动,睡眠}模式

 // Each element then alternates between delay, vibrate, sleep, vibrate, sleep
 notificationBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000}); 
Run Code Online (Sandbox Code Playgroud)