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()' –