美文网首页
android之NotificationManager服务

android之NotificationManager服务

作者: Lee_5566 | 来源:发表于2021-02-03 19:36 被阅读0次
    image.png

    NotificationManager

    NotificationManager是一个Android系统服务,用于管理和运行所有通知。

    NotificationManager因为是系统服务,所以不能被实例化,为了把Notification传给它,可以用getSystemService()方法获取一个NotificationManager的引用。

    在需要通知用户时再调用notify()方法将Notification对象传给它。

    使用实例:

     NotificationManager notificationManager = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
     notificationManager.notify(id, builder.build());
    

    不同android版本上通知功能

    • Android 4.1(API 级别 16)
      引入了展开式通知模板(称为通知样式),可以提供较大的通知内容区域来显示信息。用户可以使用单指向上/向下滑动的手势来展开通知。
    • Android 5.0(API 级别 21)
      引入了锁定屏幕和浮动通知
      向 API 集添加了通知是否在锁定屏幕上显示的方法 (setVisibility()),以及指定通知文本的“公开”版本的方法。
      添加了 setPriority() 方法,告知系统该通知应具有的“干扰性”(例如,将其设置为“高”,可使该通知以浮动通知的形式显示)。
    • Android 7.0(API 级别 24)
      用户可以使用内联回复直接在通知内回复(用户可以输入文本,然后将其发送给通知的父级应用)。
    • Android 8.0(API 级别 26)
      现在必须将单个通知放入特定渠道中。
      用户现在可以按渠道关闭通知,而不是关闭应用的所有通知。
      包含活动通知的应用会在应用图标上方显示通知“标志”。(小圆点或数字)
      用户可以暂停抽屉式通知栏中的通知。您可以为通知设置自动超时。
      可以设置通知的背景颜色。

    通知式样介绍

    image.png
    • ① 小图标:此为必要图标,通过 setSmallIcon() 设置。
    • ② 应用名称:此由系统提供。
    • ③ 时间戳:此由系统提供,不过您可以通过 setWhen() 进行替换,或使用 setShowWhen(false) 将其隐藏。
    • ④ 大图标:此为可选图标(通常仅用于联系人照片;请勿将其用于应用图标),通过 setLargeIcon() 设置。
    • ⑤ 标题:此为可选内容,通过 setContentTitle() 设置。
    • ⑥ 文本:此为可选内容,通过 setContentText() 设置。

    实战

    注意:实验过程中发现在模拟机上可以正常执行,但是真机却执行失败,最后发现真机上需要在设置里,打开通知的权限。

    思路:

    1. 创建渠道:在android8.0以上需要创建,以下不用创建
    2. 设置点击事件
    3. 构造Notification对象并显示通知

    代码

    mainActivity.java:

    package com.exmple.hooknotify;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.NotificationCompat;
    
    import android.app.Notification;
    import android.app.NotificationChannel;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import java.time.format.TextStyle;
    
    public class MainActivity extends AppCompatActivity {
    
        Button button;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            button = (Button)findViewById(R.id.buttonOne);
    
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    NotificationManager notificationManager = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
    
                    Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
    
                    String channelId = createNotificationChannel("my_channel_ID", "my_channel_NAME", NotificationManager.IMPORTANCE_HIGH);
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, channelId)
                            .setContentTitle("通知")
                            .setContentText("你好,世界!")
                            .setContentIntent(pendingIntent)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setAutoCancel(true)
                            .setWhen(System.currentTimeMillis());
    
    
                    notificationManager.notify(16657, notification.build());
                }
            });
    
    
        }
    
        private String createNotificationChannel(String channelID, String channelNAME, int level) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
                manager.createNotificationChannel(channel);
                return channelID;
            } else {
                return null;
            }
        }
    
    }
    

    mainActivity2.java

    package com.exmple.hooknotify;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    
    public class MainActivity2 extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
        }
    }
    

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/buttonOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送消息"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    activity_main2.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity2">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello world"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    运行效果:


    image.png
    image.png

    相关文章

      网友评论

          本文标题:android之NotificationManager服务

          本文链接:https://www.haomeiwen.com/subject/lfestltx.html