Android Notification使用

简介

  虽然Toast类是一种显示用户警报的非常便利的方法,但是它不是持久的。它会在屏幕上显示几秒钟之后就消失。如果它包含了非常重要的信息,如果用户没有看屏幕,他们很可能会错过它。

  对于非常重要的信息,需要使用更加持久的方法。在这种情况下,就要使用NotificationManager在设备顶部显示一条持久的信息,这块区域通常称作状态栏(有时也称为通知栏)。

Notification方法

  Notification(int icon, CharSequence tickerText, long when)

常用方法

返回类型函数函数说明
Notification.BuilderaddAction(int icon, CharSequence title, PendingIntent intent)这个方法在API 23中被弃用了,API 23以上使用addAction(Action)。
Notification.BuilderaddAction(Notification.Action action)为Notification添加一个动作。
Notificationbuild()生成一个配置好的Notification实例。
Notification.BuildersetContentIntent(PendingIntent intent)当Notification被点击的时候,将触发这个PendingIntent。
Notification.BuildersetContentText(CharSequence text)设置Notification通知面板中的第二行文字内容(Text)。
Notification.BuildersetContentTitle(CharSequence title)设置Notification通知面板中的第一行文字内容(Title)。
Notification.BuildersetLargeIcon(Bitmap b)为Notification通知面板添加一个大图标。
Notification.BuildersetLargeIcon(Icon icon)为Notification通知面板添加一个大图标。
Notification.BuildersetOngoing(boolean ongoing)设置该通知是否允许持续不断的,持续不断的通知有如下特征:
1.处于正在进行的服务面板,在正常通吃面板的上方。
2.不允许出现“X”关闭按钮,并且清除全部对其毫无作用。
Notification.BuildersetOnlyAlertOnce(boolean onlyAlertOnce)当onlyAlertOnce被设置为true的时候,Notification只被播放一次,即声音、震动、条状通知将只出现一次。
Notification.BuildersetSmallIcon(int icon, int level)当添加的icon是一个层级图片的时候,可以使用level设置层级。
Notification.BuildersetSmallIcon(int icon)为Notification的通知面板添加一个小图标。这个小图标在使用的时候会被呈现到状态栏上。
Notification.BuildersetSmallIcon(Icon icon)为Notification的通知面板添加一个小图标。这个小图标在使用的时候会被呈现到状态栏上和Notification上的内容栏上(除非被大图标所覆盖)。
Notification.BuildersetSound(Uri sound, AudioAttributes audioAttributes)为Notification添加声音,参数为sound的Uri地址,也可以通过参数streamType使用自定义的流类型设置声音。
Notification.BuildersetSound(Uri sound)该方法在API 26中已被弃用。API 26以上使用setSound(Uri, AudioAttributes)代替。
Notification.BuildersetSound(Uri sound, int streamType)该方法在API 21中已被弃用。API 21以上使用setSound(Uri, AudioAttributes)代替。
Notification.BuildersetStyle(Notification.Style style)设置Notification的风格。
Notification.BuildersetTicker(CharSequence tickerText, RemoteViews views)setTicker(CharSequence)的废弃版本。
Notification.BuildersetTicker(CharSequence tickerText)设置Notification通知面板中的tickerText
Notification.BuildersetVibrate(long[] pattern)该方法在API 26中已被弃用。使用setVibrationPattern(long[])代替。
Notification.BuildersetWhen(long when)设置通知时间。通知面板依据时间排序通知条。

使用教程

  AndroidManifest

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

    <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>

        <!--设置NotificationView-->
        <activity  android:name=".NotificationView" android:label="Details of notification">
            <intent-filter>
                <!--使用Intent过滤器-->
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

  NotificationView

public class NotificationView extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notification);
        //---look up the notification manager service---
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //---cancel the notification that we started---
        assert nm != null;
        Bundle bundle = getIntent().getExtras();
        assert bundle != null;
        nm.cancel(bundle.getInt("notificationID"));
    }
}

  MainActivity

public class MainActivity extends AppCompatActivity {
    int notificationID = 1;

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

    private void displayNotification() {
        Intent i = new Intent(this, NotificationView.class);
        i.putExtra("notificationID", notificationID);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, i, 0);
        NotificationManager nm = (NotificationManager) getSystemService
                (NOTIFICATION_SERVICE);
        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this, this.getPackageName())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("会议提醒")
                .setContentText("内容: 敌军将在五秒钟后到达!")
                .addAction(R.mipmap.ic_launcher, "Notzuonotdied",
                        pendingIntent);
        assert nm != null;
        nm.notify(notificationID, notifBuilder.build());
    }

    public void onClick(View view) {
        displayNotification();
    }
}

  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="link_work.myapplication.MainActivity">

    <Button  android:id="@+id/btn_display_notif" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClick" android:text="@string/notification" />

</LinearLayout>

  notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

    <TextView  android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:gravity="center" android:text="@string/notification_hint" android:textSize="20sp" />

    <TextView  android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="@string/notification_content" />
</RelativeLayout>

效果演示

《Android Notification使用》

说明

PendingIntent

  PendingIntent和Intent有稍微的区别。

类型说明
Intent及时启动,随所在的Activity消失而消失。
PendingIntent延迟执行的Intent,用于处理即将发生的事件。

  几个主要的方法:

方法说明
PendingIntent.getActivity(Context context, int requestCode, Intent intent, @Flags int flags)该方法返回的PendingIntent可以用于启动一个Activity。
PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags)该方法用于从系统中获取一个PendingIntent对象,用于向BroadcastReceiver发送Intent。
PendingIntent getService(Context context, int requestCode, @NonNull Intent intent, @Flags int flags)该方法从系统中获取一个PendingIntent对象,用于启动一个Service。

  PendingIntent的两个主要的方法如下:

方法说明
public void send()该方法主要用于触发PendingIntent的Intent行为,通过参数中的Intent启动一个Activity、Service,或者向BroadcastReceiver发送一个Intent。
public void cancel()该方法用于取消一个已经触发了的PendingIntent。只有PendingIntent的源应用程序才有权限调用cancel方法,把它从系统中移除掉。

NotificationManager介绍

  NotificationManager是所有通知的管理类,负责发送通知、消除通知等操作。NotificationManager支持ToastNotification两种通知方式,前者相当于一个定时关闭的对话框,后者在状态栏上显示一条消息。ToastNotification都可以随时取消。NotificationManager不能实例化,可以通过getSystemService(String)方法来获得,代码如下所示:

NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

  NotificationManager有三种常用方法:

方法说明
public void cancel(int id)表示该通知能被状态栏的清除按钮清除掉。
public void cancelAll()移除所有已经显示的通知。
public void notify(int id, Notification notification)提交一个通知在状态栏中显示。如果拥有相同标签和相同id的通知已经被提交而且没有被移除,该方法会更新之前的通知。
    原文作者:Notzuonotdied
    原文地址: https://blog.csdn.net/notzuonotdied/article/details/78882290
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞