当有新通知到达时,常常以响铃方式提醒用户。这里主要讲怎么通过简单的代码来播放系统默认的铃声。请参阅下面的关键代码:
import java.util.Random; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.media.AudioManager; public class TipHelper { // 播放默认铃声 // 返回Notification id public static int PlaySound(final Context context) { NotificationManager mgr = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification nt = new Notification(); nt.defaults = Notification.DEFAULT_SOUND; int soundId = new Random(System.currentTimeMillis()) .nextInt(Integer.MAX_VALUE); mgr.notify(soundId, nt); return soundId; } }
该方法的参数,传递Activity的引用即可。当然,上面的代码,在静音模式下,是无法播放的。