《第一行代码》第二版 学习总结18 通知

      最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。

      今天主要说一下Android系统中的通知机制;也就是我们常常在状态栏上的通知消息,比如短信没有读了,微信来信息了,手机电量低了等等。当然,这一部分需要用到真机测试;不然部分效果展示不出来;所以最好先找一部手机并且调出开发者模式,而且电脑上装一个可以安装手机驱动的软件比如豌豆荚示例代码下载链接

1,通知的概念与知识点的使用

      通知主要应用于后台在运行的程序发出给用户的通知消息,它可以在活动,广播接收器以及服务中创建。但是由于其应用场景的限制,所以较少在活动中创建;但是不管在什么地方,使用流程都是一样的;下面我也就结合书本对其进行三重讲解;基本使用,进阶使用以及高级使用;最后说一下通知的优先级即可,所以内容如下:

  • 基本使用
  • 进阶使用
  • 高级使用
  • 通知优先级

(1)在基本使用里面,我们主要使用到以下几个知识点:

  • NotificationManager : 通知管理者
  • Notification :通知
  • NotificationCompat.Builder:用于获取通知实例并设置通知相关的参数(主要API)
  • PendingIntent :另一种意图,在合适的时机执行意图动作,主要实现通知详细信息的展示

(2)在进阶的使用里面,主要使用的是以下知识点:

  • NotificationCompat.Builder里面的setVibrate()
  • NotificationCompat.Builder里面的setLights()
  • NotificationCompat.Builder里面的setSound()
  • Uri的基本使用

(3)在高级使用里面,主要使用以下知识点:

  • NotificationCompat.Builder里面的setStyle()

 (4) 在通知优先级里面,使用了以下知识点:

  • NotificationCompat.Builder里面的setPriority()

      从上面可以看出,在通知的使用过程中,NotificationCompat.Builder是一个很重要的API;下面就来结合具体的示例代码分析一下使用

2,示例代码

MainActivity.java代码:

package com.hfut.notificationtest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.File;

/**
 * 关于通知的测试,主要知识点:
 * NotificationManager,Notification,NotificationCompat.Builder的使用
 */

public class MainActivity extends AppCompatActivity {

    NotificationManager manager;
    int basicNotificationID = 10;
    int juniorNotificationID = 20;
    int higherNotificationID = 30;

    int priorityID = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //第一步:
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }


    //基本通知实现,就只是简单显示通知消息
    public void setBasicNotification(View view) {
        /**
         * 没有配置通知详细展示页面
         */
//        //第二步:
//        Notification notification = new NotificationCompat.Builder(this)
//                .setContentTitle("初级通知"+basicNotificationID)
//                .setContentText("你有一条未读消息")
//                .setWhen(System.currentTimeMillis())
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setAutoCancel(true)
//                .build();
//        //第三步:
//        manager.notify(notificationID, basicNotificationID);
//        basicNotificationID++;


        /**
         * 配置通知详细展示页面
         */

        //第二步:
        Intent intent = new Intent(this, BaseNotificationInfoPage.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        //第三步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("初级通知" + basicNotificationID)
                .setContentText("你有一条初级未读消息")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();
        //第四步:
        manager.notify(basicNotificationID, notification);
        basicNotificationID++;
    }


    //在通知的时候,添加声音和震动,闪烁灯提示
    // ,这里声音直接使用读取本地文件的方式
    public void setJuniorNotification(View view) {

        //第二步:
        Intent intent = new Intent(this, MiddleNotificatiobInfoPage.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        //第三步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("中级通知" + juniorNotificationID)
                .setContentText("你有一条中级未读消息")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                //添加音频文件路径
                .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Aquila.ogg")))
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setVibrate(new long[]{0, 500, 1000, 500})
                //添加未读消息提示灯,亮起时长,暗去时长
                .setLights(Color.RED, 2000, 2000)
                .setAutoCancel(true)
                .build();
        //第四步:
        manager.notify(juniorNotificationID, notification);
        juniorNotificationID++;

    }

    //实现在通知状态栏显示富文本和图片,主要通过setStyle()和NotificationCompat对象
    //因为长文本和大图片在通知中用得不多,简单写一下,不多说
    public void setHigherNotification(View view) {

        //第二步:
        Intent intent = new Intent(this, HighNotificationInfoPage.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        //第三步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("高级通知" + higherNotificationID)
                .setContentText("你有一条初级未读消息")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                //长文本
//                .setStyle(new NotificationCompat.BigTextStyle().bigText("\"KKKKKKKKKKKKKKKKKKKKKK\" +\n" +
//                        "                        \"KKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLl\" +\n" +
//                        "                        \"LLLLLLLLLLLLLLLLLLLLl\""))


                //大图片
                .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(
                        getResources(), R.drawable.base
                )))

                .setAutoCancel(true)
                .build();
        //第四步:
        manager.notify(higherNotificationID, notification);
        higherNotificationID++;
    }


    /**
     * 通知优先级测试
     */

    //最小优先级通知
    public void minNotification(View view) {

        //第二步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("最小优先级通知")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //添加音频文件路径
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setAutoCancel(true)
                .build();
        //第三步:
        manager.notify(priorityID, notification);
        priorityID++;
    }

    //低优先级通知
    public void lowNotification(View view) {

        //第二步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("low优先级通知")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //添加音频文件路径
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setAutoCancel(true)
                .build();
        //第三步:
        manager.notify(priorityID, notification);
        priorityID++;

    }

    //默认优先级通知
    public void defaultNotification(View view) {

        //第二步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("default优先级通知")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //添加音频文件路径
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setAutoCancel(true)
                .build();
        //第三步:
        manager.notify(priorityID, notification);
        priorityID++;
    }

    //高优先级通知
    public void highNotification(View view) {

        //第二步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("high优先级通知")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //添加音频文件路径
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setAutoCancel(true)
                .build();
        //第三步:
        manager.notify(priorityID, notification);
        priorityID++;
    }

    //最高优先级通知
    public void maxNotification(View view) {

        //第二步:
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("max优先级通知")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //添加音频文件路径
                //添加震动,第一,延时;第二:震动时长;第三:延时;第四:震动时长
                .setAutoCancel(true)
                .build();
        //第三步:
        manager.notify(priorityID, notification);
        priorityID++;
    }

    /**
     * 实现清除已有通知
     */
    public void clearAllNotification(View view) {
        manager.cancelAll();
    }

}

BaseNotificationInfoPage.java代码:

package com.hfut.notificationtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class BaseNotificationInfoPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_info_page);
    }
}

MiddleNotificationInfoPage.java代码:

package com.hfut.notificationtest;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

/**
 * @author why
 * @date 2018-3-14 9:28:46
 * @desc
 */
public class MiddleNotificatioInfoPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_middle_notificatio_info_page);

    }
}

HighNotificationInfoPage.java代码:

package com.hfut.notificationtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class HighNotificationInfoPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_high_notification_info_page);
    }
}

activity_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.notificationtest.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="setBasicNotification"
        android:text="@string/baseNotificationButton" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="setJuniorNotification"
        android:text="@string/middleNotificationButton" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="setHigherNotification"
        android:text="@string/highNotificationButton" />

    <TextView
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/priority"
        android:textSize="30dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="70dp"
            android:onClick="minNotification"
            android:text="min" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="lowNotification"
            android:text="low" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="defaultNotification"
            android:text="default" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="highNotification"
            android:text="high" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="maxNotification"
            android:text="max" />

    </LinearLayout>

    <Button
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="clearAllNotification"
        android:text="@string/clearAll" />

</LinearLayout>

activity_notification_info_page.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.notificationtest.BaseNotificationInfoPage">

<ImageView
    android:layout_marginTop="30dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/base"/>

    <TextView
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:textColor="#DC143C"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/baseNotification" />

</LinearLayout>

activity_middle_notification_info_page.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.notificationtest.MiddleNotificatioInfoPage">

    <ImageView
        android:layout_marginTop="30dp"
        android:src="@drawable/middle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/middleNotification" />

</LinearLayout>

activity_high_notification_info_page.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.notificationtest.MiddleNotificatiobInfoPage">

    <ImageView
        android:layout_marginTop="30dp"
        android:src="@drawable/high"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/highNotification" />

</LinearLayout>

主配置文件AndroidManifest.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hfut.notificationtest">

    <!-- 震动权限 -->
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BaseNotificationInfoPage" />
        <activity
            android:name=".MiddleNotificatiobInfoPage"
            android:label="@string/title_activity_middle_notificatiob_info_page"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".HighNotificationInfoPage"></activity>
    </application>

</manifest>

对了,还有一个res/values目录下的strings.xml文件:

<resources>
    <string name="app_name">NotificationTest</string>
    <string name="baseNotification">你今天的学习任务还没有完成,抓紧时间哟!</string>
    <string name="middleNotification">你好呀,今天的任务还有一点点就完成了,加油哟!</string>
    <string name="highNotification">恭喜恭喜,你今天的任务已经圆满完成了,可以去休息一会了。</string>
    <string name="clearAll">清除所有通知</string>
    <string name="priority">通知优先级测试</string>
    <string name="highNotificationButton">高级通知测试</string>
    <string name="middleNotificationButton">中级通知测试</string>
    <string name="baseNotificationButton">基础通知测试</string>
    <string name="title_activity_middle_notificatiob_info_page">MiddleNotificatiobInfoPage</string>
</resources>

 

3,运行结果:

 

第一步:运行程序:

                                     

                                                                                                 图 1

 

第二步:依次点击“基础通知测试”,“中级通知测试”,“高级通知测试”

                               

                                                                                                 图 2

 

第三步:下拉状态栏,观察通知消息;

                                 

                                                                                                  图 3

 

第四步:随便选择一条通知点开,比如点开“初级通知10”;

                                   

                                                                                                 图 4

第五步:返回,点击“清除所有通知”按钮;

                                 

                                                                                                  图 5

总结:最后的结果操作部分,没有详细展开;可以自己多尝试一下;还有就是代码里面也有很多细节,比如:

(1)点击通知之后,通知图标怎么就消失了

(2)通知的id每一个都要保证不一样

(3)扩展:怎么实现将清除通知做成手机上那样,点一个“叉”的符号就全部消失

(4)通知的优先级怎么体现出来的

(5)提供一个查找RGB颜色值对应16进制颜色码的网页,点击查看

注:欢迎扫码关注

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值