android notification 無法發出聲音解決辦法
android小白,在學習第一行代碼的時候發現程序無法發出通知,摸索了半天,查了很多資料,解決方法如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build(); channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes); manager.createNotificationChannel(channel); }
Intent intent = new Intent(this, NotificationActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0 ,intent, 0); Button sendNotice = (Button) findViewById(R.id.send_notice); sendNotice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Notification notification = new NotificationCompat.Builder(MainActivity.this, "normal") .setContentTitle("This is content title") .setContentText("This is content text") .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .setContentIntent(pi) // .setAutoCancel(true) // .setDefaults(Notification.DEFAULT_SOUND) // .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg"))) // .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .build(); manager.notify(1, notification); } });