我的代码有什么问题 - 通知 - 没有声音也没有震动

10

我似乎在我的代码中遇到了问题。 我创建了一个测试活动,只是为了看看哪里出了问题,但我还是找不到原因。

public class test extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String extra = "test";

    NotificationManager myNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, test.class);

    Notification notification = new Notification(R.drawable.icon, 
            extra, 
            System.currentTimeMillis());
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(getApplicationContext(), "title", "text", pendingIntent);
    notification.flags |= Notification.DEFAULT_SOUND;
    notification.flags |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.DEFAULT_VIBRATE;
    notification.flags |= Notification.FLAG_INSISTENT;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    myNotificationManager.notify(33, notification);

}
}
我收到通知时没有声音和/或振动。
我查看了手机的设置,它们都是正确的,没有静音,启用默认声音。
2个回答

17

This...

notification.flags |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.DEFAULT_VIBRATE;

应该是...

notification.defaults|= Notification.DEFAULT_SOUND;
notification.defaults|= Notification.DEFAULT_LIGHTS;
notification.defaults|= Notification.DEFAULT_VIBRATE;

13

您可以使用一行代码设置所有默认值(声音、振动和灯光):

notification.defaults = Notification.DEFAULT_ALL;

这相当于

notification.defaults|= Notification.DEFAULT_SOUND;
notification.defaults|= Notification.DEFAULT_LIGHTS;
notification.defaults|= Notification.DEFAULT_VIBRATE;

请确保在您的清单文件中设置了振动权限

<uses-permission android:name="android.permission.VIBRATE" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接