那些年开发通知栏遇到的坑

来源:互联网 发布:淘宝网怎么没有一淘了 编辑:程序博客网 时间:2024/06/06 01:08

1.Android通知栏在项目开发中,还是用的比较多的,一般是这三个步骤来做Android通知栏:

    (1)获取通知栏管理器对象

   NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   (2)创建通知对象,并设置ui
  NotificationCompat.Builder builder = new NotificationCompat.Builder(GlobalApplication.globalContext);  builder.setSmallIcon(R.drawable.smalleIcon);    builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.largeIcon));  builder.setContentTitle(title);   //通知栏标题  builder.setContentText(progress + "%");     //通知栏内容  Notification notification = builder.build(); 
   (3)发送通知
  mNotificationManager.notify(id,notification);

2.通知栏的其他api

   (1)通知栏的移除:mNotificationManager.cancle(id);        //该id需要同发送通知的id一致

   (2)点击事件处理:

    // 构建一个Intent      Intent resultIntent = new Intent(NotificationActivity.this,  TestActivity.class);              resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK                      | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);          // 封装一个PendingIntent       PendingIntent resultPendingIntent = PendingIntent.getActivity(NotificationActivity.this, 0, resultIntent,  PendingIntent.FLAG_UPDATE_CURRENT);       // 设置通知主题的意图        builder.setContentIntent(resultPendingIntent);  

3.注意问题:

 (1)使用系统样式必须设置三个属性,否则崩溃。

  setContentText()  setContentTitle()  setSmallIcon()
  (2)下载更新进度时,必须控制更新频率(或者不设置largeIcon),否则部分手机(nexus)会导致内存溢出崩溃。我们可以定时更新,这样进度会跳跃式前进,市场上大部分都是这么做的。 
    private NotificationCompat.Builder getNotification(String title, int progress) {        //设置通知的标题        builder.setContentTitle(title);        if (progress >= 0) {            //当progress大于或等于0时,才需要显示下载进度            MyLogUtil.i(TAG + "---getNotification--progress:" + progress);            builder.setContentText(progress + "%");            builder.setProgress(100, progress, false);        }        return builder;    }
  (3)自定义通知栏样式时,问题更多,且适配是个问题(背景色各不一致),一般还是不建议这么做了。
   在使用remoteView时,layout需要注意控件的使用(只能是AnalogClock,Button,Chronometer,ImageButton,mageView,ProgressBar,TextView这7种),且宽度必须为0,wrap_content,或match_parent,fill_parent不可用。




原创粉丝点击