android Notifications通知

1.Notifications超越屏幕上的UI.
首先在布局中定义两个Button控件
在这里插入图片描述
2.在MainActivity中写应用程序,可以发送通知和清除通知.

package com.example.android00010;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private final int NOTIFYID_ID=0X23;  //定义一个常量
    
    private Button button1;
    private Button button2;
    private Button button3;
    private int i=0;


    //创建一个通知管理器,发送通知
   private NotificationManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);
        button3=findViewById(R.id.button3);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  //初始化
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button1:
                i++;
                createNotification();
                break;
            case R.id.button2:
                manager.cancel(NOTIFYID_ID);
                break;

            case R.id.button3:


                break;
        }
        }

    /*
    发送通知  打开通知
     */
    public void createNotification(){
      Notification.Builder builder=new Notification.Builder(this);
      builder.setSmallIcon(R.drawable.ic_launcher_background);//设置图标
      builder.setContentTitle("通知");  //标题
      builder.setContentTitle("你有"+i+"条信息未发送");//设置内容
      builder.setWhen(System.currentTimeMillis()); //设置时间
     

      //发送 唤醒
      manager.notify(NOTIFYID_ID,builder.getNotification()); //给一样id他会累加信息
        }



        /*
        打开通知
         */

}

2.打开通知,在定义一个布局控件(context.xml)和活动ContentActivity
在这里插入图片描述
在这里插入图片描述

3.打开通知,在调用.
在这里插入图片描述

发布了60 篇原创文章 · 获赞 3 · 访问量 2193

猜你喜欢

转载自blog.csdn.net/ysy_1_2/article/details/104349325