notificationcompat setDefaults和setting

时间:2012-11-26 16:17:54

标签: android-notifications

我正在为我的android项目添加通知:

mBuilder.setContentTitle("title");
mBuilder.setContentText("Text");
mBuilder.setSmallIcon(R.drawable.icon);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mBuilder.setSound(Uri.parse("android.resource://com.my.package/" + R.raw.sound));
mBuilder.setOnlyAlertOnce(true);

现在,我想要一个“设置视图”,用户可以决定他/她是否需要振动或发声。

我应该如何存储此设置并更新setDefaults和setSound?

2 个答案:

答案 0 :(得分:2)

SharedPreferences是一个很好的起点。

答案 1 :(得分:1)

来自@dsandler,我举一个例子作为一个更详细的例子:

builder = new NotificationCompat.Builder(this).setContentTitle(contentTitle).setContentText(contentText).setSmallIcon(R.drawable.ic_launcher)
            .setAutoCancel(true).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));

    int notificationDefault = NotificationCompat.DEFAULT_SOUND;

    // Check vibrate
    boolean isVibrate = mPreferences.getBoolean(mKeyPrefNotifications[1], true);
    if (isVibrate) {
        notificationDefault = notificationDefault | NotificationCompat.DEFAULT_VIBRATE;
    }

    // Check light
    boolean isLight = mPreferences.getBoolean(mKeyPrefNotifications[2], true);
    if (isLight) {
        notificationDefault = notificationDefault | NotificationCompat.DEFAULT_LIGHTS;
    }

    // Check sound
    Uri sound = null;
    if (!mPreferences.contains(mKeyPrefNotifications[3])) {
        sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    } else {
        String soundPref = mPreferences.getString(mKeyPrefNotifications[3], "");
        if (soundPref.isEmpty()) {
            sound = null;
        } else {
            sound = Uri.parse(soundPref);
        }
    }

    builder.setDefaults(notificationDefault);
    builder.setSound(sound);