Android Notification

通知(Notification)是Android系统比较有特色的一个功能,当某个应用程序希望向用户发出一些提示信息,而该应用程序又不再前台运行,就可以借助通知来实现.
1.通知的基本用法
通知即可以在活动里创建,也可以在广播接收器里创建,不论在哪里创建,整体步骤都是相同的,首先需要一个NotificationManager来对通知进行管理,可以调用Context的getSystemService()方法来获取到,getSystemService()方法接收一个字符串参数用于确定获取系统的哪个服务,这里我们传入Context.NOTIFICATION_SERVICE.代码如下所示:

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

接下来需要使用一个Builder构造器来创建一个Notification对象.support-v4库中提供了一个NotificationCompat类,使用这个类的构造器来创建Notification对象,就可以保证我们的程序在所有Android系统版本上都能正常工作,代码如下所示:

Notification notification = new NotificationCompat.Builder(context).build();

上述代码只是创建了一个空的Notification对象,并没有什么实际作用,我们可以在最终的builder()方法之前连缀任意多的设置方法来创建一个丰富的Notification对象,代码如下所示:

Notification notification = new NotificationCompat.Builder(context)
    .setContentTitle("This is content title")
    .setContentText("This is content text")
    .setWhen(System.currentTimeMillis())
    .setSmallIcon(R.drawable.small_icon)
    .setLargeIcon(BitmapFactory.decodeResource(getResource(),R.drawable.large_icon))
    .build();

上述代码一共调用了5个设置方法,setContentTitle()方法用于指定通知的标题内容,下拉系统状态栏就可以看到这部分内容,setContentText()用于指定通知的正文,同样下拉系统状态栏就可以看到这部分内容,setWhen()方法用于指定通知被创建的时间,以毫秒为单位,当下拉系统状态栏时,这里指定的时间会显示在相应的通知上,setSmallIcon()方法用于设置通知的小图标,注意只能使用纯alpha图层的图片进行设置,小图标会显示在系统状态栏上,setLargeIcon()方法用于设置通知的大图标,当下拉系统状态栏时,就可以看到设置的大图标了.
然后只要调用NotificationManager的notify()方法就可以让通知显示出来,notify()方法接收两个参数,第一个参数是id,要保证为每个通知所指定的id都是不同的,第二个参数则是Notification对象,代码如下:

manager.notify(1, notification);

写一个简单的栗子
修改activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/send_notice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send notice" />

</LinearLayout>

修改MainActivity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button)findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }
    @Override
    public void onClick(View v){
        switch(v.getId){
            case R.id.send_notice:
                NotificationManager manager =(NotificationManager)getSystemService
                    (NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(context)
                    .setContentTitle("This is content title")
                    .setContentText("This is content text")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.small_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResource(),R.drawable.large_icon))
                    .build();
                manager.notify(1, notification);
                break;
            default:
                break;
        }
    }
}

通知的点击响应,我们需要在代码中进行相应的设置,PendingIntent从名字上看起来就和Intent类似,它们之间也确实存在不少共同点,比如都可以去指明某一个”意图”,都可以用于启动活动,启动服务以及发送广播.不同的是Intent更加倾向于去立即执行某个动作,而PendingIntent更加倾向于在某个合适的时机去执行某个动作,所以,也可以把PendingIntent简单的理解为延迟执行的Intent.
PendingIntent主要提供几个静态方法用于获取PendingIntent的实例,可以根据需求来选择是使用getActivity()方法,getBroadcast()方法,还是getService()方法,这几个方法所接收的参数都是相同的,第一个参数是Context,第二个参数一般用不到,通常传入0,第三个参数是一个Intent对象,我们可以通过这个对象构建出PendingIntent的”意图”.第四个参数用于确定PendingIntent的行为,有FLAG_ONE_SHOT,FLAG_NO_CREATE,FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT这四个值可选,通常情况下这个参数传入0即可.

NotificationCompat.Builder这个构造器还可以再连缀一个setContentIntent()方法,接收的参数正是一个PendingIntent对象,因此,这里可以通过PendingIntent构建出一个延迟执行的”意图”,当用户点击这条通知的时候就会执行相应的逻辑

具体代码如下:
添加一个布局名为notification_layout.xml代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:text="This is notification layout" />

</RelativeLayout>

修改MainActivity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ...
    @Override
    public void onClick(View v){
        switch(v.getId){
            case R.id.send_notice:
                Intent intent = new Intent(this, NotificationActivity.class);
                PendingIntent pi = PendingIntent.getActivity(this, 0, intnet, 0);
                NotificationManager manager =(NotificationManager)getSystemService
                    (NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(context)
                    .setContentTitle("This is content title")
                    .setContentText("This is content text")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.small_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResource(),R.drawable.large_icon))
                    .setContentIntent(pi)
                    .build();
                manager.notify(1, notification);
                break;
            default:
                break;
        }
    }
}

这里先使用Intent表达出我们想要启动NotificationActivity的”意图”,然后将构建好的Intent对象传入到PendingIntent的getActivity()方法里,以得到PendingIntent的实例,接着在NotificationCompat.Builder中调用setContentIntent()方法,把它作为参数传入即可.

你会方法当点击通知进入的时候系统状态栏上的通知图标没有消失,因为我们没有在代码中对该通知进行取消,解决办法是:一种是在NotificationCompat.Builder中再连缀一个setAutoCancel()方法,一种是显示的调用NotificationManager的cancel()方法将它取消
第一种代码如下:

Notification notification = new NotificationCompat.Builder(this)
    ...
    .setAutoCancel(true)
    .build();

第二种代码如下:

public class NotificationActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification_layout);
        NotificationManager manager =(NotificationManager)getSystemService
                    (NOTIFICATION_SERVICE);
        manager.cancel(1);  
        //取消那条通知,在cancel()方法中传入该通知的id
    }
}

2.通知的进阶技巧
setSound()方法,可以在通知发出的时候播放一段音频,setSound()方法接收一个Uri参数,所以在指定音频文件的时候还需要先获取到音频文件对应的URI,比如每个手机的/system/media/audio/ringtones目录下都有很多的音频文件,我们可以从中随便选一个,例如:

 Notification notification = new NotificationCompat.Builder(this)
     ...
     .setSound(Uri.formFile(new File("/system/media/audio/ringtones/Luna.ogg")))
     .build();

除了允许播放音频外,我们还可以在通知到来的时候让手机振动,使用的是vibrate这个属性,它是一个整型的数组,用于设置手机静止和振动的时长,以毫秒为单位,下标为0的值表示手机静止的时长,下标为1的值表示手机振动的时长,下标为2 的值又表示手机静止的时长,以此类推.所以,如果想要让手机在通知到来时立刻振动1秒,然后静止1秒,再振动1秒,可以这样写:

 Notification notification = new NotificationCompat.Builder(this)
     ...
     .setVibrate(new long[] {0, 1000, 1000, 1000})
     .build();

想要控制手机振动还需要声明权限,修改AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notificationtest"
    android:versionCode="1"
    android:versionName="1.0">
    ...
    <uses-permission android:name="android.permission.VIBRATE" />
    ...
</manifest>

在通知到来时控制手机LED灯的显示,使用setLights()方法来实现,setLights()方法接收3个参数,第一个参数用于指定LED灯的颜色,第二个参数用于指定LED灯亮起的时长,以毫秒为单位,第三个参数用于指定LED灯暗去的时长,也是以毫秒为单位,所以,当通知到来时,如果想要实现LED灯以绿色的光一闪一闪的效果,代码如下:

 Notification notification = new NotificationCompat.Builder(this)
     ...
     .setLights(Color.GREEN, 1000, 1000)
     .build();

如果不想进行那么多繁杂的设置,也可以直接使用通知的默认效果,它会根据当前的手机环境来决定播放什么铃声,以及如何振动,代码如下:

Notification notification = new NotificationCompat.Builder(this)
     ...
     .setDefaults(NotificationCompat.DEFAULT_ALL)
     .build();

3.通知的高级功能
setStyle()方法,这个方法允许我们构建出富文本的通知内容,也就是说通知中不光可以有文字和图标,还可以包含更多的东西,setStyle()方法接收一个NotificationCompat.style参数,这个参数就是用来构建具体的富文本信息的,如长文字,图片等,

通知内容设置成很长的文字代码:

Notification notification = new NotificationCompat.Builder(this)
     ...
     .setContentText("Learn how to build notifications, send and sync data, and use  voice actions, Get the official Android IDE and developer tools to build apps for Android.")
     ...
     .build();

可以看到,通知的内容是无法显示完整的,多余的部分会用省略号来代替,
想要在通知中显示一段很长的文字,通过setStyle()方法也可以做到,代码如下:

Notification notification = new NotificationCompat.Builder(this)
     ...
     .setStyle(new NotificationCompat.BigTextStyle().bigText("Learn how to build notifications, send and sync data, and use  voice actions, Get the official Android IDE and developer tools to build apps for Android."))
     ...
     .build();

在setStyle()方法中创建了一个NotificationCompat.BigTextStyle对象,这个对象用于封装长文字信息,调用它的bigText()方法并将文字内容传入即可

除了显示长文字外,通知里还可以显示一张大图,具体用法也是基本相似的:

Notification notification = new NotificationCompat.Builder(this)
     ...
     .setStyle(new NotificationCompat.BigPictureStyle().bigPicture("BitmapFactory.decodeResource(getResources(), R.drawable.big_image)"))
     ...
     .build();

这里调用setStyle()方法,在参数中创建一个NotificationCompat.BigPictureStyle对象,这个对象就是用于设置大图片的,然后调用它的bigPicture()方法并将图片传入,图片通过BitmapFactory的decodeResource()方法解析成Bitmap对象,再传入到bigPicture()方法中就可以了.

setPriority()方法,它可以用于设置通知的重要程度,setPriority()方法接收一个整型参数用于设置通知的重要程度,一共有5个常量值可选,PRIORITY_DEFAULT表示默认的重要程度,和不设置效果是一样的,PRIORITY_MIN表示最低的重要程度,系统可能只会在特定的场景才会显示这条通知,比如用户下拉状态栏的时候,PRIORITY_LOW表示较低的重要程度,系统可能会将这类通知缩小,或改变其显示顺序,将其排在更重要的通知之后,PRIORITY_HIGH表示较高的重要程度,系统可能会将这类通知放大,或改变其显示的顺序,将其排在比较靠前的位置,PRIORITY_MAX表示最高的重要程度,这类通知消息必须要让用户立刻看到,甚至需要用户做出响应操作,具体代码如下:

Notification notification = new NotificationCompat.Builder(this)
     ...
     .setPriority(NotificationCompat.PRIORITY_MAX)
     ...
     .build();

这里我们将通知的重要程度设置成了最高,表示这是一条非常重要的通知,要求用户必须立刻看到.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值