我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的。
- package cn.com.chenzheng_java;
- import android.app.Activity;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.Intent;
- import android.net.Uri;
- import android.os.Bundle;
- import android.provider.MediaStore.Audio;
- import android.view.View;
- import android.widget.Button;
- /***
- * @description 状态栏通知相关
- * @author chenzheng_java
- *
- */
- public class NotificationActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.notification);
- Button button = (Button) findViewById(R.id.button);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- addNotificaction();
- }
- });
- }
- /**
- * 添加一个notification
- */
- private void addNotificaction() {
- NotificationManager manager = (NotificationManager) this
- .getSystemService(Context.NOTIFICATION_SERVICE);
- // 创建一个Notification
- Notification notification = new Notification();
- // 设置显示在手机最上边的状态栏的图标
- notification.icon = R.drawable.excel;
- // 当当前的notification被放到状态栏上的时候,提示内容
- notification.tickerText = "注意了,我被扔到状态栏了";
- /***
- * notification.contentIntent:一个PendingIntent对象,当用户点击了状态栏上的图标时,该Intent会被触发
- * notification.contentView:我们可以不在状态栏放图标而是放一个view
- * notification.deleteIntent 当当前notification被移除时执行的intent
- * notification.vibrate 当手机震动时,震动周期设置
- */
- // 添加声音提示
- notification.defaults=Notification.DEFAULT_SOUND;
- // audioStreamType的值必须AudioManager中的值,代表着响铃的模式
- notification.audioStreamType= android.media.AudioManager.ADJUST_LOWER;
- //下边的两个方式可以添加音乐
- //notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
- //notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
- Intent intent = new Intent(this, Notification2Activity.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
- // 点击状态栏的图标出现的提示信息设置
- notification.setLatestEventInfo(this, "内容提示:", "我就是一个测试文件", pendingIntent);
- manager.notify(1, notification);
- }
- }
点击按钮时候,状态栏会显示:
看到了吧,状态栏多出来一个excel图标,当我按住图标不放,往下拖动的时候,出来了这个页面
然后,当我们点击这个对话框之后,就会触发intent,跳转到Notification2Activity.java这个activity。
----------------------------------------------------------------------------------------
注意,NotificationManager里的notify(id,notification)中的id是用来唯一标识我们当前的这个notification的标识符,我们通过cancel方法删除通知时,传递的就是这个值。可能读者在看很多文档的时候,发现这个地方指定了一个莫名奇妙的值,例如R.drawable.icon,很多朋友就纳闷了,为什么这里要指定一个图片呢。这里笔者就介绍下,为什么呢?
答案其实很简单,我们都知道,我们这里对参数的唯一要求就是,这个id要和notify方法中的一致,并且是唯一;只要满足了这两项,其他的都无所谓。notify和cancel里一致我们作为开发者,太好控制了,但是唯一呢,我们还真不好说,于是这里就有些人动小脑筋了,很巧妙的用了我们系统中的图片资源或者其他资源的索引ID,我们都知道,这些值肯定都是唯一的!