Android Notification通知的简单使用

运行效果:

前言:

Notification,是一种具有全局效果的通知,可以在系统的通知栏中显示。当 APP 向系统发出通知时,它将先以图标的形式显示在通知栏中。用户可以下拉通知栏查看通知的详细信息。通知栏和抽屉式通知栏均是由系统控制,用户可以随时查看。

View层布局:添加一个按钮用于发送消息。

Control层代码:

public class MainActivity extends AppCompatActivity {

    public static final int NOTIFICCATION_ID=1200;
    private int count=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Notification.Builder builder=new Notification.Builder(MainActivity.this);// 使用建造者模式构建 Notification 对象
                builder.setSmallIcon(R.mipmap.ic_launcher_round);//设置图标
                builder.setContentTitle("有个好消息!");//主标题设置
                builder.setContentText("你第"+count+"对象找你了!");//内容文字
                Notification notification=builder.build();//创建notification对象
                NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                //NotificationManager:是状态栏通知的管理类,负责发通知、清除通知等。
                //NotificationManager 是一个系统Service,必须通过 getSystemService()方法来获取。
                //使用NotificationManager获取系统的Notification服务
                manager.notify(NOTIFICCATION_ID,notification);
                //唤醒正在此对象监视器上等待的单个线程。如果任何线程正在等待此对象,则选择其中一个线程被唤醒。
                //通过NotificationManager的notify(int, Notification) 方法来启动Notification。
                //第一个参数唯一的标识该Notification,第二个参数就是Notification对象。
                count++;
            }
        });
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章