Notification应用(包括添加为“正在进行的”)

本文详细介绍了如何在Android应用中创建不同类型的通知,包括普通通知、进行中的通知以及如何设置标志位来实现持续或进行中的通知。通过示例代码展示了如何使用NotificationManager及Notification类。

1. 普通的通知:

/**
     * 开启通知
     */
    public void startNotification()
    {
      NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         Notification notification = new Notification(R.drawable.icon, "金仔音乐播放器", System.currentTimeMillis());
           notification.setLatestEventInfo(getApplicationContext(), "金仔音乐播放器","正在运行", PendingIntent.getActivity(
                        MyMediaPlayer.this, 0,new Intent(MyMediaPlayer.this,MyMediaPlayer.class), 0));
        notification.flags|=Notification.FLAG_AUTO_CANCEL;
         notification.defaults |= Notification.DEFAULT_SOUND;
        manager.notify(1, notification);
    }

 

2. 添加为正在进行的通知

    String service = Context.NOTIFICATION_SERVICE;
    NotificationManager manager = (NotificationManager)getSystemService(service);
    //实例化Notification
    Notification notification = new Notification();
    notification.icon = R.drawable.icon;
    notification.tickerText = "金仔音乐播放器";
    notification.when = System.currentTimeMillis();
    //显示在“正在进行中”
    notification.flags = Notification.FLAG_ONGOING_EVENT;

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

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//设置启动模式,防止创建新的activity
    //获得PendingIntent
    PendingIntent pIntent = PendingIntent.getActivity(MyMediaPlayer.this, 0, intent, 0);
    //设置事件信息,显示在拉开的里面
    notification.setLatestEventInfo(MyMediaPlayer.this, "金仔音乐播放器", "正在运行", pIntent);
    //发出通知
    manager.notify(1,notification);

3. 设置 FLAG_INSISTENTFLAG_ONGOING_EVENT标志位让Notification成为持续或正在进行的通知;

    正在进行的事件与“普通的”Notification区别在扩展的状态条窗口中

    (1)正在进行的:notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

     (2)持续的Notification一直重复,直到用户取消:notification.flags = notification.flags | Notification.FLAG_INSISTENT;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值