Android本地通知

时间:2013-11-24 06:39:20

标签: android notifications

当某些事件发生时,我需要在标题栏的android中显示本地通知。我希望通知也播放一定的声音。

点击通知我想要app不应该启动,并且应该清除通知。

我正在使用此代码,但点击通知后再次打开我的应用。

        CharSequence title = "App title";
        CharSequence message = "This to alert you that estimated time is getting complete.";

        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, "Title", System.currentTimeMillis());

        Intent notificationIntent = new Intent(this, JobView.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(JobView.this, title, message, null);
        notificationManager.notify(1010, notification);

2 个答案:

答案 0 :(得分:0)

CharSequence title = "App title";
CharSequence message = "This to alert you that estimated time is getting complete.";

NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "Title", System.currentTimeMillis());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

builder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.YOUR_SOUND_FILE);
notificationManager.notify(1234, builder.build());

只需从代码中的Raw文件夹中替换文件参考,代码就可以正常工作 我希望这会有所帮助。

答案 1 :(得分:0)

试试这个:

CharSequence title = "App title";
CharSequence message = "This to alert you that estimated time is getting complete.";

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                  .setSmallIcon(R.drawable.ic_launcher)
                  .setAutoCancel(true)
                  .setContentTitle(title);

mBuilder.setSound(Uri.parse("android.resource://"
                  + this.getPackageName() + "/" + R.raw.sound));
mBuilder.setContentText(message);
mBuilder.setTicker(message);
mBuilder.setWhen(System.currentTimeMillis());

NotificationManager notificationManager =   
       (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
mBuilder.setContentIntent(pendingIntent);
notificationManager.notify(1010, mBuilder.build());  

使用声音文件的路径更改R.raw.sound