6

首先我已经检查了所有这些链接:振动推送通知

但我无法实现我的手机震动,当我收到推送通知。这里去我的代码:

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()); 
    } 
} 

权限

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

测试

设备:Nexus 5的

Android版本:6.0.1

有某种未知的巫术,我应该做的,使其工作?

+0

你可能要检查这个SO [解决方案](http://stackoverflow.com/a/36869888/5995040)或[这里]( http://stackoverflow.com/a/33951000/5995040)。这可能会帮助你解决你的问题。 –

+0

@Rebot先生对于延迟回复,我感到抱歉,但没有任何解决方案适用于我! :( – guisantogui

回答

9

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

值应该是以下字段与按位或组合的一个或多个(|):DEFAULT_SOUNDDEFAULT_VIBRATEDEFAULT_LIGHTS

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

Ex。根据你的代码要设置默认的声音所以,如果你想设置默认的声音和振动:

notificationBuilder.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE); 

如果你希望所有的默认设置,你可以通过设置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}); 
0

这震动电话:

Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE); 
// Vibrate for 500 milliseconds 
v.vibrate(500); 

当您打电话通知还称这

+0

man我没有任何mContext在我的服务里面,但是我可以在没有它的情况下调用getSystemService,但是它不会振动:( – guisantogui

+0

)mContext是上下文,你可以使用'getActivity()' –