Contents
  1. 1. 2015-10-03 14:53:24
    1. 1.0.1. 自定义Notification

2015-10-03 14:53:24

自定义Notification

  • 由于getNotificatoin()方法已经过时,因此要实现Notification就用Notification.Builder()的build方法。
  • 通常Notification的用法如下:

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification.Builder(SettingActivity.this)
            .setContentTitle("版本更新")//设置标题
            .setSmallIcon(R.mipmap.ic_launcher)//图标
            .setContentInfo("GDPC")//设置右边的小提示
            .setAutoCancel(false) // 设置点击取消(貌似无效)
            .setTicker("有新版本了") //状态栏显示收到的消息
            .setDefaults(Notification.DEFAULT_VIBRATE)//设置震动
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) //设置声音
            .build();
    manager.notify(0,notification); // 发送通知
    
  • 如果要使用自定义Notification 需要用到RemoteViews的构造方法装载布局(统一使用该API的方法来设置布局里的控件)

     RemoteViews rv = new RemoteViews(getPackageName(), R.layout.activity_test);
    rv.setTextViewText(R.id.tvTestFuntion, "我是自定义的 notification");
    notification.contentView = rv; // 初始化RemoteViews
    

    使用RemoteView可以会报下列错误,这是因为布局activity_test中使用了RemoteView不支持的控件,例如View。

    android.app.RemoteServiceException: Bad notification posted from XXX
    
在RemoteViews这种调用方式中,你只能使用以下几种界面组件:  

Layout: 

    FrameLayout, LinearLayout, RelativeLayout

Component: 

      AnalogClock, Button, Chronometer, ImageButton, ImageView, ProgressBar, TextView, ViewFlipper, ListView, GridView, StackView, AdapterViewFlipper
  • Intent与PendingIntent联合使用,实现点击消息进行跳转页面。

    1. Intent用于设置跳转的Activity。
    2. PendingIntent用于设置将要跳转的Intent。
  •  Intent myIntent = new Intent(SettingActivity.this, AboutUsActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(SettingActivity.this, 0, myIntent, 0);//装载Intent
    notification.contentIntent = pendingIntent;//初始化PedingIntent
    
Contents
  1. 1. 2015-10-03 14:53:24
    1. 1.0.1. 自定义Notification