Android 如何以正确的方式设置通知声音持续时间
我是android新手。我正在尝试创建一个具有自定义声音持续时间的通知。我见过很多有这个功能的应用程序,但我不知道如何以最有用的方式来实现它 对于我的通知,我使用Android 如何以正确的方式设置通知声音持续时间,android,notifications,android-notifications,Android,Notifications,Android Notifications,我是android新手。我正在尝试创建一个具有自定义声音持续时间的通知。我见过很多有这个功能的应用程序,但我不知道如何以最有用的方式来实现它 对于我的通知,我使用BroadcastReceiver: public class NotificationAlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { setNotification(c
BroadcastReceiver
:
public class NotificationAlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
setNotification(context);
}
private void setNotification(Context context) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
(int) System.currentTimeMillis(), intent, 0);
Notification notification = new Notification.Builder(context).
setTicker("Hi!").
setAutoCancel(true).
setContentTitle("Bla bla lba!").
setContentText("Hi hi!").
setSmallIcon(R.mipmap.ic_launcher).
setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.FLAG_INSISTENT;
notificationManager.notify((int) System.currentTimeMillis(), notification);
}
}
谢谢 我找不到任何控制声音持续时间的方法,但您可以使用以下代码使AudioManager.STREAM\u通知静音:-
final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setStreamMute(AudioManager.STREAM_NOTIFICATION, true or false);
不要忘记在通知声音总持续时间结束后将其取消静音。我找到了一个非常适合我的解决方案 因此,您应该启动一个线程,该线程可以根据需要休眠尽可能多的时间,然后将当前通知替换为相同的通知,但没有任何声音/振动等
new Thread() {
public void run() {
try {
sleep(duration * DateUtils.SECOND_IN_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
notificationManager.cancel(id);
//start the same notification without sound
soundlessNotification(context);
}
}.start();